【问题标题】:Appending grandtotal and subtotal rows to two-level row and column index dataframe将总计和小计行附加到两级行和列索引数据帧
【发布时间】:2018-02-08 20:05:38
【问题描述】:
import pandas, io

data = io.StringIO('''Fruit,Color,Count,Price
Apple,Red,3,1.29
Apple,Green,9,0.99
Pear,Red,25,2.59
Pear,Green,26,2.79
Lime,Green,99,0.39
''')
df_unindexed = pandas.read_csv(data)
df = df_unindexed.set_index(['Fruit', 'Color'])
grandtotal=df.sum().to_frame().T
subtotal=df.sum(axis=0,level=[0])

df
Out[830]: 
             Count  Price
Fruit Color              
Apple Red        3   1.29
      Green      9   0.99
Pear  Red       25   2.59
      Green     26   2.79
Lime  Green     99   0.39

grandtotal
Out[831]: 
   Count  Price
0  162.0   8.05

subtotal
Out[832]: 
       Count  Price
Fruit              
Apple     12   2.28
Lime      99   0.39
Pear      51   5.38

1) 我如何将总计附加为第一行(保持原始数据框格式)

1a) 另外我想将行索引移动到顶行,以便我可以将这些单元格用于 ('All Fruits','Total')

2) 我如何将小计附加到每个水果的顶部?

2a) 我有两个索引的小计行

期望的输出:

Fruit   Color   Count   Price
All Fruits  Total   162 8.05
Apple   Subtotal    12  2.28
Apple   Red 3   1.29
Apple   Green   9   0.99
Peer    Subtotal    51  5.38
Pear    Red 25  2.59
Pear    Green   26  2.79
Lime    Subtotal    99  0.39
Lime    Green   99  0.39

【问题讨论】:

    标签: database pandas sum concat multi-index


    【解决方案1】:

    使用pd.concatassignsumset_index

    df_out = pd.concat([df,
                        df.sum(level=0).assign(Color='SubTotal')\
                          .set_index('Color', append=True),
                        df.sum().to_frame().T\
                          .assign(Fruit='All Fruit', 
                                  Color='Total')\
                          .set_index(['Fruit', 'Color'])])\
               .sort_index()
    

    输出:

                       Count  Price
    Fruit     Color                 
    All Fruit Total     162.0   8.05
    Apple     Green       9.0   0.99
              Red         3.0   1.29
              SubTotal   12.0   2.28
    Lime      Green      99.0   0.39
              SubTotal   99.0   0.39
    Pear      Green      26.0   2.79
              Red        25.0   2.59
              SubTotal   51.0   5.38
    

    【讨论】:

    • 这是完美的。我不得不以不同的方式重新调整小计和总计行。
    • 我很高兴它有帮助。编码愉快!
    • 您能推荐任何用于多索引操作的视频/资料吗?有什么好的熊猫教程吗?
    • 实际上,pandas 文档在这方面做得很好。除此之外,我的大部分学习都在这里,Stack Overflow。提问可以得到比我聪明得多的人的帮助,而且回答问题是学习 Pandas 的好方法。
    • 很抱歉打扰您,但您怎么知道要回答问题?您是否在 Stackoverflow 上单独注册?
    猜你喜欢
    • 2020-10-26
    • 2019-01-03
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多