在数据透视表上放置两个“行标签”(Excel 术语)后,我试图按降序对数据透视表的值进行排序。
示例数据:
x = pd.DataFrame({'col1':['a','a','b','c','c', 'a','b','c', 'a','b','c'],
'col2':[ 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3],
'col3':[ 1,.67,0.5, 2,.65, .75,2.25,2.5, .5, 2,2.75]})
print(x)
col1 col2 col3
0 a 1 1.00
1 a 1 0.67
2 b 1 0.50
3 c 1 2.00
4 c 1 0.65
5 a 2 0.75
6 b 2 2.25
7 c 2 2.50
8 a 3 0.50
9 b 3 2.00
10 c 3 2.75
为了创建枢轴,我使用了以下函数:
pt = pd.pivot_table(x, index = ['col1', 'col2'], values = 'col3', aggfunc = np.sum)
print(pt)
col3
col1 col2
a 1 1.67
2 0.75
3 0.50
b 1 0.50
2 2.25
3 2.00
c 1 2.65
2 2.50
3 2.75
换句话说,这个变量 pt
首先按 col1
排序,然后按 col1
中的 col2
的值排序然后通过所有这些中的 col3
。这很好,但我想按 col3
(值)排序,同时保留在 col2
中分解的组(此列可以是任何顺序并随机排列).
目标输出看起来像这样(col3
以降序排列,col2
中的任意顺序与那组 col1
):
col3
col1 col2
a 1 1.67
2 0.75
3 0.50
b 2 2.25
3 2.00
1 0.50
c 3 2.75
1 2.65
2 2.50
我已经尝试了下面的代码,但这只是对整个数据透视表值进行排序并丢失了分组(我正在寻找组内排序)。
pt.sort_values(by = 'col3', ascending = False)
作为指导,这里提出(并回答)了一个类似的问题,但我无法使用提供的输出获得成功的输出:
我从那个答案中得到的错误是ValueError: all keys need to be the same shape
最佳答案
你需要reset_index
对于 DataFrame
,然后是 sort_values
通过 col1
和 col3
和最后 set_index
对于 MultiIndex
:
df = df.reset_index()
.sort_values(['col1','col3'], ascending=[True, False])
.set_index(['col1','col2'])
print (df)
col3
col1 col2
a 1 1.67
2 0.75
3 0.50
b 2 2.25
3 2.00
1 0.50
c 3 2.75
1 2.65
2 2.50
关于python-3.x - 排序数据透视表(多索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45300428/