我有两个数据帧df1和df2,我被告知共享一些行。也就是说,对于某些索引,(i,j)_n df1.loc [i] == df2.loc [j]。我想找到这封信。
追踪这是一个棘手的问题。我不想“手动”查询每一行的每一列,所以我一直在寻找更清洁的东西。
这是我所拥有的最好但却不快。我希望一些大师可以指出我正确的方向。
matching_idx=[]
for ix in df1.index:
match =df1.loc[ix:ix].to_dict(orient='list')
matching_idx.append( df2.isin(match).all(axis=1) )
摆脱for循环会很好,但我不确定它是否可能。
答案 0 :(得分:1)
假设每个数据帧中的行都是唯一的,您可以连接两个数据帧并搜索重复数据。
df1 = pd.DataFrame({'A': ['a', 'b'], 'B': ['a', 'c']})
df2 = pd.DataFrame({'A': ['c', 'a'], 'B': ['c', 'a']})
>>> df1
A B
0 a a
1 b c
>>> df2
A B
0 c c
1 a a
df = pd.concat([df1, df2])
# Returns the index values of duplicates in `df2`.
>>> df[df.duplicated()]
A B
1 a a
# Returns the index value of duplicates in `df1`.
>>> df[df.duplicated(keep='last')]
A B
0 a a
答案 1 :(得分:1)
您可以执行连接所有列的合并:
match = df1.merge(df2, on=list(df1.columns))