将总计和小计行附加到两级行和列索引数据框
Appending grandtotal and subtotal rows to two-level row and column index dataframe
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
使用 pd.concat
、assign
、sum
和 set_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
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
使用 pd.concat
、assign
、sum
和 set_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