Pandas透视表 - 添加总计和更改顺序

3
我有以下样例代码:
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

如何开始做这个?谢谢!
1个回答

5
使用 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

非常好,谢谢。手动选择水果的顺序怎么样,而不是按字母顺序排列? - caddie
请参考 https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Categorical.html 和 https://dev59.com/q2Yr5IYBdhLWcg3wOX66。 - BENY
成功了!我使用了pd.Categorical手动分配到水果系列中的任何排序。非常感谢! - caddie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接