[英]How do I compare two data frames to show the difference?
我正在尝试比较两个不同大小的 excel 文件,一个有 5701 行,另一个有 5904 行。 列是价格和项目描述。 我正在尝试通过文本进行比较以查看项目差异是什么。
import pandas as pd
import numpy as np
df = pd.read_csv('C:/Users/Text/Downloads/D1.csv')
df2 = pd.read_csv('C:/Users/Text/Downloads/D2.csv')
df['text_match'] = np.where(df['Project ID'] == df2['Project ID'], 'True', 'False')
print(df.loc[(df['text_match'] == 'False')])
当我尝试运行代码时出现以下错误:
raise ValueError("Can only compare identically-labeled Series objects")
ValueError: Can only compare identically-labeled Series objects
比较 2 个 dfs - 记录数必须相同:
您可以使用:
df1.equals(df2)
然后得到 - 错误,没有比较的选项。
可以选择使用:
df1.reset_index(drop=True) == df2.reset_index(drop=True)
还有另一种选择 - 将第二个 df 剪切为(5701 行)
# Number of rows to drop
n = 203
# Removing last n rows
df2 = df2.iloc[:-n]
可以使用Pandas.compare .compare()
function,如下:
df.compare(df2)
样本output如下:
col1 col3
self other self other
0 a c NaN NaN
2 NaN NaN 3.0 4.0
它突出了df
与self
和df2
与other
的区别
您可以通过例如比较部分列
df[['Project ID', 'Price']].compare(df2[['Project ID', 'Price']])
或者,如果您只想比较Project ID
列:
df['Project ID'].compare(df2['Project ID'])
另一种方法是使用.isin()
尝试过滤不匹配的Project ID
,如下所示:
df.loc[~df['Project ID'].isin(df2['Project ID'])]
和:
df2.loc[~df2['Project ID'].isin(df['Project ID'])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.