我试图从Pandas pivot_table创建一个简单的数据透视表,但我无法关闭输出表中Values名称的排序。
参数“sort = False”仅有助于关闭索引名称中的排序。
import pandas as pd
data = {
"StateName" : ["Manipur", "Manipur", "Assam", "Chennai", "Delhi", "Delhi", "Assam"],
"Male Accounts" : [121, 987, 1043, 34, 209, 89, 90],
"Female Accounts" : [23, 890, 2012, 7810, 765, 902, 23],
"Small Accounts" : [90, 21, 98, 45, 56, 34, 90],
"Current Accounts" : [121, 623, 90, 76, 23, 87, 91]
}
df = pd.DataFrame(data)
print(df)
pv_table = pd.pivot_table(df, index = "StateName", sort = False, aggfunc = 'sum')
print(pv_table)
输出:
StateName Male Accounts Female Accounts Small Accounts Current Accounts
0 Manipur 121 23 90 121
1 Manipur 987 890 21 623
2 Assam 1043 2012 98 90
3 Chennai 34 7810 45 76
4 Delhi 209 765 56 23
5 Delhi 89 902 34 87
6 Assam 90 23 90 91
Current Accounts Female Accounts Male Accounts Small Accounts
StateName
Manipur 744 913 1108 111
Assam 181 2035 1133 188
Chennai 76 7810 34 45
Delhi 110 1667 298 90
正如您所看到的,Values列标题在这里按字母顺序排序。是否有任何方法可以关闭此排序。
预期输出:
2条答案
按热度按时间ruarlubt1#
TBH我不会让列重新排序,但你总是可以将列更改为所需的顺序:
hmae6n7t2#
看起来
sort=False
工作正常(1.3.0版本中的新功能,从1.5.0开始工作正常):相关: