【问题标题】:How do I compare two data frames to show the difference?如何比较两个数据框以显示差异?
【发布时间】:2021-11-25 21:30:45
【问题描述】:

我正在尝试比较两个大小不同的 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

【问题讨论】:

  • 这两个文件的标题是什么?

标签: python pandas dataframe error-handling


【解决方案1】:

要比较 2 个 dfs - 记录数必须相同:

你可以使用:

df1.equals(df2)

然后get - false,没有比较的选项。

有使用选项:

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]

【讨论】:

【解决方案2】:

可以使用Pandas的@​​987654321@函数,如下:

df.compare(df2)

示例输出如下:

  col1       col3
  self other self other
0    a     c  NaN   NaN
2  NaN   NaN  3.0   4.0

它突出了selfdfotherdf2 的区别

您可以通过例如比较部分列

df[['Project ID', 'Price']].compare(df2[['Project ID', 'Price']])

或者,如果您只想比较 Project ID 列:

df['Project ID'].compare(df2['Project ID'])

另一种方法是尝试过滤不匹配的Project ID,使用.isin(),如下:

df.loc[~df['Project ID'].isin(df2['Project ID'])]

和:

df2.loc[~df2['Project ID'].isin(df['Project ID'])]

【讨论】:

  • 我尝试了 df1.compare(df2),它收到以下错误:ValueError: Can only compare same-labeled DataFrame objects
  • @MDL7833 这两个数据框的列标签不同?您可以先重命名其中一个
  • @MDL7833 您还可以限制要比较的列数。请参阅上面的编辑。
  • @MDL7833 另见通过.isin() 过滤不匹配的Project ID 的替代方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 2017-07-11
  • 1970-01-01
  • 2015-08-10
  • 2017-05-10
  • 1970-01-01
相关资源
最近更新 更多