两个 DataFrame 之间的不匹配行
我是 Python 新手,想寻求您的帮助。 我想找出 2 个数据帧(即 df1 和 df2)之间有数千行的不匹配行。它们都包含相同数量且具有相同名称的列。
df2 有 10 个比 df1 少的条目,我正在尝试找出它们是什么。 我已尝试 pd.concat([df1,df2]).drop_duplicates(keep=False)
但它返回零结果。
可能是什么原因? 任何帮助/建议将不胜感激。 多谢。
I am new to Python and would like to seek you help on this please.
I would like to find out the non-matching rows between 2 dataframes i.e. df1 and df2 with thousands of rows. They both contain the same number of columns with the same name.
df2 has 10 entries lesser than df1 which I am trying to find out what they are.
I have tried pd.concat([df1,df2]).drop_duplicates(keep=False)
but it returns zero result.
What could be the reason?
Any help/advice would be much appreciated.
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
concat
组合两个框架。您正在尝试找出两个框架之间的差异。这可以通过比较来完成。正如文档示例所示,给定这两个框架:
df = pd.DataFrame(
{
"col1": ["a", "a", "b", "b", "a"],
"col2": [1.0, 2.0, 3.0, np.nan, 5.0],
"col3": [1.0, 2.0, 3.0, 4.0, 5.0]
},
columns=["col1", "col2", "col3"],
)
df2 = df.copy()
df2.loc[0, 'col1'] = 'c'
df2.loc[2, 'col3'] = 4.0
您可以使用 compare
找到不同的行:
df.compare(df2)
col1 col3
self other self other
0 a c NaN NaN
2 NaN NaN 3.0 4.0
在这种情况下,compare
为每一行有差异的行返回一行,并且仅实际上不同的列。
compare
也可以返回相等的值或所有原始值:
df.compare(df2, keep_equal=True)
col1 col3
self other self other
0 a c 1.0 1.0
2 b b 3.0 4.0
或
df.compare(df2, keep_shape=True, keep_equal=True)
col1 col2 col3
self other self other self other
0 a c 1.0 1.0 1.0 1.0
1 a a 2.0 2.0 2.0 2.0
2 b b 3.0 3.0 3.0 4.0
3 b b NaN NaN 4.0 4.0
4 a a 5.0 5.0 5.0 5.0
仅仅因为您的条目少了 10 个,并不意味着您会找到重复项。您可能在第一个数据框中已经有重复项。
演示:
# Length: 7
df1 = pd.DataFrame({'col1': list('AAABCDE'),
'col2': list('FFFGHIJ'),
'col3': list('1112345')})
# Length: 5
df2 = pd.DataFrame({'col1': list('ABCDE'),
'col2': list('FGHIJ'),
'col3': list('12345')})
您的代码:
>>> pd.concat([df1,df2]).drop_duplicates(keep=False)
Empty DataFrame
Columns: [col1, col2, col3]
Index: []
尝试:
>>> len(df1.drop_duplicates())
5
>>> len(df2.drop_duplicates())
5
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
以下代码将删除
df1
中存在于df2
中的行The following code will remove rows in
df1
that are present indf2