【问题标题】:How can I compare two columns of two different data frame and add new resultant column如何比较两个不同数据框的两列并添加新的结果列
【发布时间】:2021-07-27 16:09:53
【问题描述】:

我有两个数据框

第一个 DF1:(7 x 3)

ID Item Qty
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 Item Qty
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 Item Qty
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'

请提出建议。

【问题讨论】:

  • 合并它们然后计算差异见pandas-merging-101
  • 合并 ID 和项目,然后 qty_x - qty_y

标签: python pandas dataframe


【解决方案1】:

在这里,合并 id 和 item:

comb = pd.merge(DF1, DF2, on=['ID', 'Item'], how='left').rename(columns={'Qty_x': 'DF1_Qty','Qty_y': 'DF2_Qty'})
comb = comb.fillna(0)
comb['Qty_new'] = comb['DF1_Qty'] - comb['DF2_Qty']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多