You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除或操作Pandas对比生成DataFrame中的self/other层级行

df.compare()返回的结果默认使用二级MultiIndex作为列名,第一级为原始数据表的字段名,第二级固定为self(对应第一张对比表df1的取值)、other(对应第二张对比表df2的取值)。针对不同操作需求可以用以下方案实现:

  • 需求1:将二级列名拍平为单层级,方便后续常规读写操作
    可以用下划线拼接两级列名,避免重名问题:

    Comparison.columns = ['_'.join(col) for col in Comparison.columns.values]
    

    处理后列名将变为First Name_self、First Name_other、Last Name_self、Last Name_other、Age_self、Age_other,转换为普通单层级DataFrame。

  • 需求2:单独提取所有self或other对应的列
    用xs方法按层级筛选列即可:

    # 提取所有self列(对应df1的全部值)
    df_self = Comparison.xs('self', level=1, axis=1)
    # 提取所有other列(对应df2的全部值)
    df_other = Comparison.xs('other', level=1, axis=1)
    

    筛选后得到的DataFrame列名就是原始的First Name、Last Name、Age,无二级层级。

  • 需求3:直接删除self/other层级(允许重名列)
    如果不需要保留self/other标识,可以直接删除二级列层级:

    Comparison.columns = Comparison.columns.droplevel(1)
    

    处理后每个原始字段对应两列重名列,分别存储df1和df2的取值,适合做同字段横向对比场景。

  • 需求4:将self/other从列层级转换为行层级
    如果需要按行维度对比两个表的取值,可以用stack方法调整层级结构:

    comparison_row = Comparison.stack(1)
    

    调整后每行索引对应(原始行号, self/other标识),每列对应原始字段名,更适合按行查看差异。

内容的提问来源于stack exchange,提问作者Kronivar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:36:02