简体   繁体   English

无论如何要重新排序 Python 中的 pivot 表列?

[英]Anyway to reorder pivot table columns in Python?

Suppose I have a pivot table like this:假设我有一个像这样的 pivot 表:

import pandas as pd

d = {'Col_A': [1,2,3,3,3,4,9,9,10,11], 
     'Col_B': ['A','K','E','E','H','A','J','A','L','A'],
     'Value1':[648,654,234,873,248,45,67,94,180,120],
     'Value2':[180,120,35,654,789,34,567,21,235,83]
    }

df = pd.DataFrame(data=d)
df_pvt = pd.pivot_table(df,values=['Value1','Value2'], index='Col_A', columns='Col_B', aggfunc=np.sum).fillna(0)
df_pvt

在此处输入图像描述

What I want to achieve is to set an order for Col_B (Highlighted) so that the outputs of Value1 and Value2 would display in this order E, J, A, K, L, H.我想要实现的是为 Col_B(突出显示)设置一个顺序,以便 Value1 和 Value2 的输出按 E、J、A、K、L、H 的顺序显示。

Convert col_B to a categorical before reshaping:在重塑之前将col_B转换为分类:

(df.astype({'Col_B' : pd.CategoricalDtype(['E', 'J', 'A', 'K', 'L', 'H'], ordered = True)})
   .pivot_table(values=['Value1','Value2'], 
                index='Col_A', 
                columns='Col_B', 
                aggfunc=np.sum)
)
      Value1                         Value2
Col_B      E   J    A    K    L    H      E    J    A    K    L    H
Col_A
1          0   0  648    0    0    0      0    0  180    0    0    0
2          0   0    0  654    0    0      0    0    0  120    0    0
3       1107   0    0    0    0  248    689    0    0    0    0  789
4          0   0   45    0    0    0      0    0   34    0    0    0
9          0  67   94    0    0    0      0  567   21    0    0    0
10         0   0    0    0  180    0      0    0    0    0  235    0
11         0   0  120    0    0    0      0    0   83    0    0    0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM