问题描述
我有 2 个大数据框,它们应该是彼此重复的。但是,第二个数据框中还有 3 行。我需要找到第一个数据帧中不存在的这 3 行额外的行,并将它们从第二个数据帧中删除,以便数据帧相同。这 3 行可以位于数据框中的任何位置,而不仅仅是添加到末尾。
我不知道解决这个问题的最有效方法。我试过同时使用 %in% 运算符!遍历数据中的每一列以查找不同的行,但由于有 100 多列,因此这花费的时间太长。 有没有人有更有效的方法来完成这样的任务?
谢谢
解决方法
我认为最有效的方法是使用第一个没有这些额外行的 data.frame
。
但是如果您需要知道它们在第二个中的位置,您可以使用以防 data.frame
的行是唯一的 duplicated
:
which(!tail(duplicated(rbind(x,y)),-nrow(x)))
#[1] 4 5
或使用 interaction
和 %in%
:
which(!interaction(y) %in% interaction(x))
#[1] 4 5
或使用 paste
和 %in%
:
which(!do.call(paste,y) %in% do.call(paste,x))
#[1] 4 5
数据:
x <- data.frame(a=1:3)
y <- data.frame(a=1:5)
,
您可以使用 anti_join 方法,但在带有数据框的 Pandas 中它们不存在...所以您可以使用 merge 来做到这一点:
def anti_join(x,y,on):
"""Return rows in x which are not present in y (dataframe)"""
ans = pd.merge(left=x,right=y,how='left',indicator=True,on=on)
ans = ans.loc[ans._merge == 'left_only',:].drop(columns='_merge')
return ans
如果你只想检查一列的第一种方法
def anti_join_all_cols(x,y):
"""Return rows in x which are not present in y"""
assert set(x.columns.values) == set(y.columns.values)
return anti_join(x,x.columns.tolist())
df 中所有列的第二个
返回只会给你 df2 中的行而不是 df,注意参数的方向,如果我们颠倒 df 和 df2,结果将不一样...
你可以:
df_difference = anti_join_all_cols(df2,df)
来源:https://gist.github.com/sainathadapa/eb3303975196d15c73bac5b92d8a210f