可以使用pandas的merge()
函数合并两个DataFrame来比较它们之间的差异。可以按照需要指定左和右边的列名来进行合并,并将on
参数设置为连接键。how
参数设置为‘outer’,以保留左右两边的所有行。然后,可以通过将列的名称从字符串更改为元组和切片来比较两个DataFrame之间的特定行。
下面是一个示例代码:
import pandas as pd
# create two sample DataFrames with different index types
df1 = pd.DataFrame({'A': [1, 1, 2, 3, 4], 'B': [5, 6, 7, 8, 9]})
df2 = pd.DataFrame({'C': [10, 11, 12, 13, 14], 'D': [15, 16, 17, 18, 19]})
df2.index = [3, 4, 5, 6, 7] # set different index
# merge the two DataFrames
merged = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
# get difference of specific rows
diff_rows = merged.loc[(2,):('3',), ('A', 'B', 'C', 'D')]
print(diff_rows)
输出结果为:
A B C D
2 2.0 7.0 NaN NaN
3 3.0 8.0 10.0 15.0
在上面的示例中,我们创建了两个不同索引类型的DataFrame,然后使用merge()
函数将它们合并。我们指定了左和右DataFrame的索引列,并将连接类型设置为‘outer’。然后,我们使用loc[]
函数按行和列选择特定的行,并计算两个DataFrame之间的差异。