在 excel 文件中显示 pandas 数据框,其中包含拆分列和合并单元格

Display pandas dataframe in excel file with split level column and merged cells

我有一个大数据框 df 作为:

Col1    Col2    ATC_Dzr ATC_Last    ATC_exp Op_Dzr2 Op_Last2
1Loc    get1    0.26    3.88        3.73    0.16    3.15
2Loc    get2    0.4     -0.85      -0.86    0.1     -0.54
3Loc    get3    -0.59   1.47        2.01    -0.53   1.29

我需要将其转储到 excel 以便它看起来如下所示:

其中 ATCOp 在合并的单元格中

我不确定如何处理这个问题?

您可以将前 2 列设置为索引并拆分其余列,expand 以创建多索引:

df1 = df.set_index(['Col1','Col2'])
df1.columns = df1.columns.str.split('_',expand=True)
print(df1)

        ATC                Op      
        Dzr  Last   exp  Dzr2 Last2
Col1 Col2                              
1Loc get1  0.26  3.88  3.73  0.16  3.15
2Loc get2  0.40 -0.85 -0.86  0.10 -0.54
3Loc get3 -0.59  1.47  2.01 -0.53  1.29

然后将 df1 导出到 excel。

根据@Datanovice 的评论,您还可以使用 Pd.MultiIndex.from_tuples:

df1 = df.set_index(['Col1','Col2'])
df1.columns = pd.MultiIndex.from_tuples([(col.split('_')[0], col.split('_')[1])
                                        for col in df1.columns])
print(df1)
          ATC                Op      
          Dzr  Last   exp  Dzr2 Last2
Col1 Col2                              
1Loc get1  0.26  3.88  3.73  0.16  3.15
2Loc get2  0.40 -0.85 -0.86  0.10 -0.54
3Loc get3 -0.59  1.47  2.01 -0.53  1.29