pandas.DataFrame.compare#
- DataFrame.compare(other, align_axis=1, keep_shape=False, keep_equal=False, result_names=('self', 'other'))[源代码]#
比较另一个 DataFrame 并显示差异。
- Parameters:
- otherDataFrame
要比较的对象。
- align_axis{0 或 ‘index’,1 或 ‘columns’},默认 1
确定对齐比较的轴。
- 0 或 ‘index’结果差异垂直堆叠
交替从 self 和 other 中提取行。
- 1 或 ‘columns’结果差异水平对齐
交替从 self 和 other 中提取列。
- keep_shapebool,默认 False
如果为 true,则保留所有行和列。否则,只保留那些具有不同值的行和列。
- keep_equalbool,默认 False
如果为 true,则结果保留相等的值。否则,相等的值显示为 NaN。
- result_namestuple, 默认 (‘self’, ‘other’)
设置比较时 DataFrame 的名称。
在 1.5.0 版本加入.
- Returns:
- DataFrame
DataFrame,显示并排堆叠的差异。
结果索引将是一个 MultiIndex,其中 ‘self’ 和 ‘other’ 在内层交替堆叠。
- Raises:
- ValueError
当两个 DataFrame 的标签或形状不相同时。
参见
Series.compare与另一个 Series 比较并显示差异。
DataFrame.equals测试两个对象是否包含相同元素。
Notes
匹配的 NaN 不会显示为差异。
只能比较具有相同标签(即形状相同、行和列标签相同)的 DataFrame。
Examples
>>> df = pd.DataFrame( ... { ... "col1": ["a", "a", "b", "b", "a"], ... "col2": [1.0, 2.0, 3.0, np.nan, 5.0], ... "col3": [1.0, 2.0, 3.0, 4.0, 5.0] ... }, ... columns=["col1", "col2", "col3"], ... ) >>> df col1 col2 col3 0 a 1.0 1.0 1 a 2.0 2.0 2 b 3.0 3.0 3 b NaN 4.0 4 a 5.0 5.0
>>> df2 = df.copy() >>> df2.loc[0, 'col1'] = 'c' >>> df2.loc[2, 'col3'] = 4.0 >>> df2 col1 col2 col3 0 c 1.0 1.0 1 a 2.0 2.0 2 b 3.0 4.0 3 b NaN 4.0 4 a 5.0 5.0
按列对齐差异。
>>> df.compare(df2) col1 col3 self other self other 0 a c NaN NaN 2 NaN NaN 3.0 4.0
分配 result_names。
>>> df.compare(df2, result_names=("left", "right")) col1 col3 left right left right 0 a c NaN NaN 2 NaN NaN 3.0 4.0
按行堆叠差异。
>>> df.compare(df2, align_axis=0) col1 col3 0 self a NaN other c NaN 2 self NaN 3.0 other NaN 4.0
保留相等的数值。
>>> df.compare(df2, keep_equal=True) col1 col3 self other self other 0 a c 1.0 1.0 2 b b 3.0 4.0
保留所有原始行和列。
>>> df.compare(df2, keep_shape=True) col1 col2 col3 self other self other self other 0 a c NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN 3.0 4.0 3 NaN NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN NaN
保留所有原始行和列,以及所有原始数值。
>>> df.compare(df2, keep_shape=True, keep_equal=True) col1 col2 col3 self other self other self other 0 a c 1.0 1.0 1.0 1.0 1 a a 2.0 2.0 2.0 2.0 2 b b 3.0 3.0 3.0 4.0 3 b b NaN NaN 4.0 4.0 4 a a 5.0 5.0 5.0 5.0