【问题标题】:How would you tell which rows were dropped from the original dataframe and the current one?您如何判断从原始数据帧和当前数据帧中删除了哪些行?
【发布时间】:2021-11-04 17:41:14
【问题描述】:
我有 2 个“完全相同”的数据框。它们之间的区别在于 DF1 有 1000 行,而 DF2 有 950 行。 50 行被删除,但想知道是什么。本质上 DF2 是 DF1 的子集,但我需要知道其他服务从其他地方丢弃了什么。
返回第 3 个数据帧 (DF3) 是最简单的方法,它显示被丢弃的数据帧 (50)。
DF3(50 行 x 4 列)= DF1(1000 行 x 4 列)- DF2(950 行 x 4 列)
索引是唯一ID。
谢谢!!
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
在索引上使用isin:
df3 = df1[~df1.index.isin(df2.index)]
【解决方案2】:
本质上 DF2 是 DF1 的子集
你是对的,所以你可以使用sets中的difference:
>>> df1.loc[df1.index.difference(df2.index)]
例子:
>>> df1
A
0 0.712755
1 0.400005
2 0.958937
3 0.112367
4 0.230177
>>> df2
A
0 0.712755
1 0.400005
4 0.230177
>>> df1.loc[df1.index.difference(df2.index)]
A
2 0.958937
3 0.112367