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

时间:2021-07-27 16:09:53

标签: python pandas dataframe

我有两个数据框

第一个 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'

请提出建议。

1 个答案:

答案 0 :(得分:1)

在这里,合并 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)
相关问题