Pandas - 在不删除索引的情况下展平多索引 table

Pandas - Flatten multi-index table without drop the index

使用原始 csv 文件,我制作了一个新的数据透视表 table:

version_pivot_table = treatcriteria_data.pivot_table(index=['version'], columns=['week'], values=['hours'], aggfunc='sum')

我得到这个table:

                              hours                               
week                             47             48             49   
version                                                
147.0.0.35            119404.056481  103956.232244            NaN   
147.1.0.4                       NaN   52494.531709  145452.572156   
148.0.0.16                      NaN            NaN            NaN

我想要这个 table,展平 table 但不删除 'version' 列,并且有一个 'Total' 行:

version                   47               48               49
147.0.0.35     119404.056481    103956.232244              NaN   
147.1.0.4                NaN     52494.531709    145452.572156 
148.0.0.16               NaN              NaN              NaN 
Total          119404.056481    156450.763954    145452.572156

编辑:感谢您的回答,但我忘记指定列的索引是整数,这分别给我这些错误消息:

ValueError: expected a value of type str, got 47 of type int

ValueError: expected a value of type str, got ('hours', 47) of type tuple

使用:

>>> version_pivot_table.droplevel(level=0, axis=1).rename_axis(index=None, columns='version')

version                47             48             49
147.0.0.35  119404.056481  103956.232244            NaN
147.1.0.4             NaN   52494.531709  145452.572156
148.0.0.16            NaN            NaN            NaN

对于 Total 行,我建议您使用 margins=Truemargins_name='Total' 作为 pivot_table 的参数,然后删除 Total 列。像这样:

version_pivot_table = \
    treatcriteria_data.pivot_table(index='version', columns='week',
                                   values='hours', aggfunc='sum',
                                   margins=True, margins_name='Total') \
                      .drop(columns='Total').droplevel(level=0, axis=1) \
                      .rename_axis(index=None, columns='version')

我忘了精确 '47'、'48'、'49' 是整数类型,我得到了这个错误信息:

ValueError: expected a value of type str, got ('hours', '47') of type tuple

我用这段代码解决了这个问题:

version_pivot_table.columns = version_pivot_table.columns.get_level_values(1)
version_pivot_table = version_pivot_table.reset_index()
version_pivot_table= version_pivot_table.append(version_pivot_table.sum(numeric_only=True), ignore_index=True)
version_pivot_table.at[len(version_pivot_table.index) - 1, 'version'] = 'Total'

结果:

           version      47       48      49
147.0.0.35_E0_V298  119404   103956                   
 147.1.0.4_E0_V299          52494.5  145453 
148.0.0.16_E0_V300                                    
             Total  119404   156451  145453