我有以下示例代码:
import pandas as pd
import numpy as np
d = {'Fruit': ['Apples', 'Oranges', 'Apples', 'Kiwi', 'Kiwi'], 'Amount':
[10, 15, 65, 5, 13]}
df = pd.DataFrame(data=d)
table = pd.pivot_table(df, index='Fruit', aggfunc= np.sum)
表结果如下所示:
Fruit Amount
Apples 75
Kiwi 18
Oranges 15
如何将总计添加到底部?另外,我想选择顺序,例如:
Fruit Amount
Oranges 15
Apples 75
Kiwi 15
Total 105
我该怎么做? 谢谢!
答案 0 :(得分:4)
使用margins
pd.pivot_table(df, index='Fruit', aggfunc= np.sum,margins = True,margins_name = 'Total')
Out[141]:
Amount
Fruit
Apples 75
Kiwi 18
Oranges 15
Total 108