Python 从数据帧中删除匹配项
我试图比较两个数据帧,然后从两个数据帧中删除匹配项 我认为Python 从数据帧中删除匹配项,python,pandas,Python,Pandas,我试图比较两个数据帧,然后从两个数据帧中删除匹配项 我认为tempSheet=tempSheet[tempSheet!=testdf]可以工作,但我得到一个错误,即 ValueError:只能比较标签相同的数据帧对象 列名是相同的,所以我猜这样做是不可能的 我是否有明显的语法错误?是否有方法使用pd.merge返回不匹配的内容 我的数据帧如下所示: Qty Price 0 1 1.30 1 6 2.70 2 8 0.20 3 10
tempSheet=tempSheet[tempSheet!=testdf]
可以工作,但我得到一个错误,即
ValueError:只能比较标签相同的数据帧对象
列名是相同的,所以我猜这样做是不可能的
我是否有明显的语法错误?是否有方法使用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]
似乎没有做任何实际的比较。我有它打印合并后,它只是df1。另外,对于删除索引,是不是
df1.drop(df1['index-1'])
?合并是否类似于pd.merge(df1、df2、on=['Qty','Price',how='INTERNAL',后缀=('-1','-2'))?相关: