我正在尝试比较两个数据帧,然后从两者中删除匹配项。
我认为 tempSheet = tempSheet[tempSheet != testdf] 可以工作,但我收到一条错误消息
ValueError:只能比较相同标签的 DataFrame 对象
列名相同,所以我猜不可能那样做。
我有明显的语法错误吗?有没有办法使用 pd.merge 返回不匹配的?
我的数据框是这样的:
Qty Price
0 1 1.30
1 6 2.70
2 8 0.20
3 10 3.90
4 9 11.25
5 15 1.89
6 26 2.67
7 200 7.65
...
Qty Price
0 1 1.30
1 10 3.90
2 15 1.89
3 16 0.98
4 2 10.52
5 66 9.87
6 9 13.42
7 43 27.65
...
我想将第一个缩减为只有火柴,所以
Qty Price
0 6 2.70
1 8 0.20
2 9 11.25
3 26 2.67
...
然后我会对第二个做同样的事情。
请您参考如下方法:
这会给你匹配的索引:
>>> hit = df1.reset_index().merge(df2.reset_index(),
... on=['Qty', 'Price'], how='inner', suffixes=('-1', '-2'))
>>> hit
index-1 Qty Price index-2
0 0 1 1.30 0
1 3 10 3.90 1
2 5 15 1.89 2
[3 rows x 4 columns]
如果你想删除匹配项,只需从 df1 中删除 index-1 并从 df2 中删除 index-2 >.
>>> df1[~df1.index.isin(hit['index-1'])] # or, df1.loc[df1.index - hit['index-1']]
Qty Price
1 6 2.70
2 8 0.20
4 9 11.25
6 26 2.67
7 200 7.65
[5 rows x 2 columns]
>>> df2[~df2.index.isin(hit['index-2'])] # or, df2.loc[df2.index - hit['index-2']]
Qty Price
3 16 0.98
4 2 10.52
5 66 9.87
6 9 13.42
7 43 27.65
[5 rows x 2 columns]
