[英]How to sort a Pandas pivot table but keep totals at end of table
我構建了一個 pivot 表來執行此操作:
prima.neta = df.pivot_table(index = ["seccion"], columns = "operacion", values = "prima_pesos", aggfunc = "sum", margins=True).fillna(0)
然后嘗試按“全部”列(由margins=True
生成)降序對表進行排序:
prima.neta.sort_values(by='All', ascending=False)
這工作正常,但原始表 output 末尾的“全部”總數(當然是最高金額)作為第一行被帶到頂部。
我想按降序對表格進行排序,但將“全部”(總計)金額保留在最后一行。
我怎樣才能做到這一點?
讓我們試試這個:
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
Output:
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
您可以交換兩行。
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)
應該有一個不那么痛苦的方法,但我不知道它是什么。
首先你必須 set_index 列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.