【发布时间】:2021-10-31 07:21:21
【问题描述】:
下面是我在 df 数据帧上使用 pivot_table 函数的代码。
df = pd.DataFrame({'State' : ['B','B','A','A','C', 'C'],
'Age' : ['1 to 5', '6 to 10', '1 to 5', '6 to 10', '1 to 5', '6 to 10'],
'Vaccinated' : [80, 20, 30, 60, 10, 15],
'Population': [100, 100, 100, 100, 100, 100],
'Percentage' : [0.80, 0.20, 0.30, 0.60, 0.10,0.15]})
df1 = pd.pivot_table(df,values=["Vaccinated", "Population","Percentage"],index=["State", "Age"], aggfunc=np.sum)
早期代码的结果:
Percentage Population Vaccinated
State Age
A 1 to 5 0.30 100 30
6 to 10 0.60 100 60
B 1 to 5 0.80 100 80
6 to 10 0.20 100 20
C 1 to 5 0.10 100 10
6 to 10 0.15 100 15
但是,我想对我的记录进行排序,使状态 B 位于顶部,然后是 A,然后是 C。 合理是因为 B 州 100% 接种了疫苗(60%+40%),A 州接种了 90%(60%+30%),C 州接种了 25%。尝试添加几次排序,我遇到了错误。
我可以咨询一下如何在 pivot_table 期间或之后添加排序条件,以便我可以实现以下结果吗?
Percentage Population Vaccinated
State Age
B 1 to 5 0.80 100 80
6 to 10 0.20 100 20
A 1 to 5 0.30 100 30
6 to 10 0.60 100 60
C 1 to 5 0.10 100 10
6 to 10 0.15 100 15
【问题讨论】:
标签: python pandas pivot-table