【问题标题】:Compare 2 datasets on multiple column criteria and find missing rows比较多个列标准的 2 个数据集并找到缺失的行
【发布时间】:2021-04-11 11:19:03
【问题描述】:

我愿意比较两个数据集:

第一:

Partner Type Power Price
Partner1 Buy 1 15.975
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Sell 1000 43.5

第二:

Partner Type Power Price
Partner1 Buy 1 15.975
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Buy 1 18.025
Partner1 Buy 2 18.025
Partner1 Sell 5 19.05
Partner1 Sell 5 19.06
Partner1 Sell 5 19.125
Partner1 Buy 2 19.2

我的目标是检查第二个表中的哪些行不存在于第一个表中,基于列“类型”、“价格”和“功率”的相等值。

compcol = ['Type','Power','Price']
missing = second[~second[compcol].isin(first[compcol].to_dict(
        orient='list')).all(axis=1)]

上面的代码确实返回了第一个表中缺少的行:

Partner Type Power Price
Partner1 Buy 2 18.025
Partner1 Sell 5 19.05
Partner1 Sell 5 19.06
Partner1 Sell 5 19.125
Partner1 Buy 2 19.2

我想要实现的是增加一行“Partner1 - BUY - 1 - 18.025”,这在第一个表中也缺少(第二个表包含 5 条具有相同数据的交易记录,而第一个表只包含4!)。

我怎样才能做到这一点?

感谢您的回答。

【问题讨论】:

  • 您能否通过使用类似df = pd.DataFrame({'Partner': [...], 'Type': [...]} 的代码 sn-p 给出两个输入数据帧的可重现示例?你也应该喜欢merge方法的熊猫文档:pandas.pydata.org/docs/reference/api/…

标签: python pandas compare multiple-columns


【解决方案1】:

您可以使用布尔掩码、isin() 方法、all() 方法和Bitwise not operator(~)

col=['Type','Power','Price']    
result=df2[~df2[col].isin(df1[col]).all(1)]

现在,如果您打印 result,您将获得所需的输出:

Partner     Type    Power   Price

5   Partner1    Buy     1   18.025
6   Partner1    Buy     2   18.025
7   Partner1    Sell    5   19.050
8   Partner1    Sell    5   19.060
9   Partner1    Sell    5   19.125
10  Partner1    Buy     2   19.200

【讨论】:

  • 谢谢你的回答,我已经试过了,但问题是我不能用 all() 屏蔽,只能屏蔽 3 列(类型、功率、价格),因为合作伙伴也可以更改.
  • 更新了我的答案,请看一看......顺便说一句,你仍然可以被所有人屏蔽 :)
  • 谢谢,它现在可以工作了!我将这 2 个表逐行连接到新表中,其中还包括第 3 行,前 2 行之间存在差异。是否可以创建一个循环,在第一行和第二行不匹配的情况下,它将第三行留空并转到下一行?我的 2 张桌子可以有不同的长度。
  • 您可以通过result=pd.concat((df1,df2),ignore_index=True) 连接newres=result.copy() 并通过newres['Price']=result['Price'].sub(result['Price'].shift(1)).dropna().reset_index(drop=True) 查找前两行之间的差异
猜你喜欢
  • 2021-12-23
  • 2022-07-27
  • 1970-01-01
  • 2021-04-15
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多