【问题标题】:Pandas Pivot_Table - Add Grand Total and change OrderPandas Pivot_Table - 添加总计并更改顺序
【发布时间】:2018-11-27 18:24:41
【问题描述】:

我有以下示例代码:

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

我该怎么做呢? 谢谢!

【问题讨论】:

    标签: pandas pivot-table


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2023-03-10
    相关资源
    最近更新 更多