可以使用pandas的compare()方法进行数据帧之间的比较。该方法将返回一个新的数据帧,其中包含两个数据帧之间不同的所有值。
首先,我们需要创建两个具有相同列但不同行的数据帧df1和df2:
import pandas as pd
data1 = {'Name': ['Amy', 'Bob', 'Chris', 'David'],
'Age': [20, 25, 30, 35],
'Salary': [25000, 35000, 45000, 55000]}
df1 = pd.DataFrame(data1)
data2 = {'Name': ['Amy', 'Bob', 'Chris', 'David', 'Emma'],
'Age': [20, 25, 30, 35, 40],
'Salary': [25000, 35000, 45000, 60000, 70000]}
df2 = pd.DataFrame(data2)
接下来,使用compare()方法来比较这两个数据帧:
compare_result = df1.compare(df2)
print(compare_result)
输出结果如下:
Salary Age
self other self other
3 55000 60000.0 35 35.0
4 NaN 70000.0 NaN 40.0
结果显示df1与df2之间有两个不同的值,一个是df1的第4行和df2的第5行之间的Salary列,另一个是df1的第4行和df2的第5行之间的Age列。
可以使用ignore_index参数将两个数据帧中不同行的索引忽略掉:
compare_result = df1.compare(df2, ignore_index=True)
print(compare_result)
输出结果如下:
Salary Age
self other self other
0 25000 25000.0 20 20.0
1 35000 35000.0 25