Remove one dataframe from another with Pandas(使用 Pandas 从另一个数据帧中删除一个数据帧)
问题描述
我有两个不同大小的数据框(df1
nad df2
).我想从 df1
中删除所有存储在 df2
中的行.
I have two dataframes of different size (df1
nad df2
). I would like to remove from df1
all the rows which are stored within df2
.
所以如果我有 df2
等于:
So if I have df2
equals to:
A B
0 wer 6
1 tyu 7
而df1
等于:
A B C
0 qwe 5 a
1 wer 6 s
2 wer 6 d
3 rty 9 f
4 tyu 7 g
5 tyu 7 h
6 tyu 7 j
7 iop 1 k
最终的结果应该是这样的:
The final result should be like so:
A B C
0 qwe 5 a
1 rty 9 f
2 iop 1 k
我能够通过使用 for 循环来实现我的目标,但我想知道是否有更好、更优雅、更高效的方式来执行此类操作.
I was able to achieve my goal by using a for loop but I would like to know if there is a better and more elegant and efficient way to perform such operation.
这是我编写的代码,以备您需要时使用:将熊猫导入为 pd
Here is the code I wrote in case you need it: import pandas as pd
df1 = pd.DataFrame({'A' : ['qwe', 'wer', 'wer', 'rty', 'tyu', 'tyu', 'tyu', 'iop'],
'B' : [ 5, 6, 6, 9, 7, 7, 7, 1],
'C' : ['a' , 's', 'd', 'f', 'g', 'h', 'j', 'k']})
df2 = pd.DataFrame({'A' : ['wer', 'tyu'],
'B' : [ 6, 7]})
for i, row in df2.iterrows():
df1 = df1[(df1['A']!=row['A']) & (df1['B']!=row['B'])].reset_index(drop=True)
推荐答案
使用merge
使用 query
,最后通过 drop
:
df = pd.merge(df1, df2, on=['A','B'], how='outer', indicator=True)
.query("_merge != 'both'")
.drop('_merge', axis=1)
.reset_index(drop=True)
print (df)
A B C
0 qwe 5 a
1 rty 9 f
2 iop 1 k
这篇关于使用 Pandas 从另一个数据帧中删除一个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Pandas 从另一个数据帧中删除一个数据帧


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01