【发布时间】: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