【问题标题】:How to sort a Pandas pivot table but keep totals at end of table如何对 Pandas 数据透视表进行排序但将总数保留在表的末尾
【发布时间】:2020-06-18 22:33:48
【问题描述】:

我为此构建了一个数据透视表:

prima_neta = df.pivot_table(index = ["seccion"], columns = "operacion", values = "prima_pesos", aggfunc = "sum", margins=True).fillna(0)

然后尝试按“All”列(由margins=True生成)按降序对表格进行排序:

prima_neta.sort_values(by='All', ascending=False)

这很好用,但是原始表格输出末尾的“全部”总数(当然是最高金额)作为第一行被带到顶部。

我想按降序对表格进行排序,但将“全部”(总计)金额保留在最后一行。

我怎样才能做到这一点?

【问题讨论】:

  • 您将不得不创建一个伪排序键。为这个问题添加一些数据。

标签: python pandas pivot-table


【解决方案1】:

让我们试试这个:

import pandas as pd
import numpy as np
np.random.seed(123)

# Create dummy dataframe
df = pd.DataFrame({'A':np.random.choice([*'ABC'], 36)
                  ,'B':np.random.choice([*'xyz'], 36)
                  ,'C':np.random.randint(0,100,36)})

# Pivot table with margins
results = df.pivot_table('C', 'A', 'B', aggfunc='sum', margins=True)

#Create temporary sortkey sort on sortkey and values, drop sortkey
result = results.assign(sortkey=results.index == 'All')\
                .sort_values(['sortkey','All'], ascending=[True, False])\
                .drop('sortkey', axis=1)
result

输出:

B      x    y    z   All
A                       
B    368  215  275   858
A    155  202  218   575
C    206  149   45   400
All  729  566  538  1833

【讨论】:

  • 哇!惊人的。工作完美。
【解决方案2】:

你可以交换两行。

ndf = df.reset_index()
totalind = ndf.index[ndf.All=='total'].tolist()[0]
ind = np.array(ndf.index)
ind[totaling], ind[-1] = ind.iloc[-1], ind.iloc[totalind]
ndf.reindex(ind)

应该有一种不那么痛苦的方法,但我不知道是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2022-08-18
    • 1970-01-01
    • 2020-06-16
    • 2012-05-22
    相关资源
    最近更新 更多