【发布时间】:2021-12-11 04:34:30
【问题描述】:
我正在比较两个包含两所学校学生信息的 excel 文件。但是,这些文件之间可能包含不同数量的行。
我使用的第一组是在两个数据框中导入excel文件:
df1 = pd.read_excel('School A - Information.xlsx')
df2 = pd.read_excel('School B - Information.xlsx')
print(df1)
Name Age Birth_Country Previous Schools
0 tom 10 USA 3
1 nick 15 MEX 1
2 juli 14 CAN 0
3 tom 19 NOR 1
print(df2)
Name Age Birth_Country Previous Schools
0 tom 10 USA 3
1 tom 19 NOR 1
2 nick 15 MEX 4
在此之后,我想检查这两个数据帧之间的差异(索引顺序并不重要)。但是,由于数据帧的大小,我收到一个错误。
compare = df1.values == df2.values
<ipython-input-9-7cc64ba0e622>:1: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
compare = df1.values == df2.values
print(compare)
False
除此之外,我想创建第三个具有相应差异的 DataFrame,以显示差异。
import numpy as np
rows,cols=np.where(compare==False)
for item in zip(rows,cols):
df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]],df2.iloc[item[0], item[1]])
但是,使用此代码不起作用,因为两个数据帧之间的索引顺序可能不同。
我的预期输出应该是以下数据框:
【问题讨论】:
-
一种方法是选择几行作为将用于比较的键,因此,例如,第一个数据帧上与
nick相关的行将是与第二个上的nick相比。但是,看看tom:在第二个数据帧上有两个名为tom的学生,那么哪一个对应于第一个数据帧上的tom?您可以使用同时使用name和age的复合键,这将打破上面示例中的平局,但是如果在同一个班级中有两个名为bob且年龄相同的学生会发生什么情况?
标签: python pandas dataframe matching