【问题标题】:Delete matches from dataframes从数据框中删除匹配项
【发布时间】:2014-04-03 19:47:49
【问题描述】:

我正在尝试比较两个数据帧,然后从两者中删除匹配项。

我认为tempSheet = tempSheet[tempSheet != testdf] 会起作用,但我收到一个错误提示

ValueError: Can only compared identically-labeled DataFrame objects

列名是相同的,所以我猜想那样做是不可能的。

我有明显的语法错误吗?有没有办法使用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
...

然后我会对第二个做同样的事情。

【问题讨论】:

标签: python pandas


【解决方案1】:

这将为您提供匹配的索引:

>>> 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]

如果您想删除匹配项,只需将 index-1df1index-2df2 删除。

>>> 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='inner', suffixes=('-1', '-2'))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 2011-10-02
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多