如何比较两个不同数据框的两列并添加新的结果列

问题描述

我有两个数据框

一个 DF1:( 7 x 3)

ID 项目 数量
123 qwe 1
123 asd 4
123 zxc 7
234 ewr 2
234 sdf 5
345 xcv 8
345 qwe 3

第二个 DF2:( 6 x 3)

ID 项目 数量
123 asd 3
123 qwe 6
234 ewr 9
234 sdf 2
345 qwe 5
345 xcv 8

我想比较 DF1 和 DF2 的 123 个 ID,并在该 ID 中比较 DF1 和 DF2 的项目数量并获得一个新列。 对其他 ID 重复相同的操作

新列在哪里

DF1['Qty_new']= DF1['Qty'] - DF2['Qty']

需要的结果:(7 x 3)

ID 项目 数量
123 qwe -5
123 asd 1
123 zxc 7
234 ewr -7
234 sdf 3
345 xcv 0
345 qwe -2

我试过使用

if (DF1['ID'] == DF2['ID']):
 while (DF1['Item'] == DF2['Item']):
  DF1['Qty_new']= DF1['Qty'] - DF2['Qty']

出现错误ValueError: Can only compare identically-labeled Series objects

也试过了

while (DF1['ID'] == DF2['ID']) & (DF1['Item'] == DF2['Item']):
 DF1['Qty_new']= DF1['Qty'] - DF2['Qty']

错误TypeError: unsupported operand type(s) for &: 'str' and 'str'

请提出建议。

解决方法

在这里,合并 id 和 item:

defaults = {None: None,'': None}


def func(arg):
    """Some function that cannot be called with None"""
    if arg is None:
        raise ValueError()
    print(f'func called with {arg}')


def foo(a):
    return defaults.get(a,True) and func(a)


def foo_b(a):
    defaults_b = {'bar': 0,**defaults}
    return defaults_b.get(a,True) and func(a)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...