我用的是熊猫0.19。在
考虑到以下数据帧:
FID admin0 admin1 admin2 windspeed population
0 cntry1 state1 city1 60km/h 700
1 cntry1 state1 city1 90km/h 210
2 cntry1 state1 city2 60km/h 100
3 cntry1 state2 city3 60km/h 70
4 cntry1 state2 city4 60km/h 180
5 cntry1 state2 city4 90km/h 370
6 cntry2 state3 city5 60km/h 890
7 cntry2 state3 city6 60km/h 120
8 cntry2 state3 city6 90km/h 420
9 cntry2 state3 city6 120km/h 360
10 cntry2 state4 city7 60km/h 740
我怎样才能创建这样的表?在
^{pr2}$我尝试使用以下透视表:
table = pd.pivot_table(df,index=["admin0","admin1","admin2"], columns=["windspeed"], values=["population"],fill_value=0)
总的来说,它工作得很好,但不幸的是,我无法按正确的顺序对新列进行排序:120km/h列出现在60km/h和90km/h列之前。如何指定新列的顺序?在
此外,作为第二步,我需要为admin0和admin1添加小计。理想情况下,我需要的表应该是这样的:
population
60km/h 90km/h 120km/h
admin0 admin1 admin2
cntry1 state1 city1 700 210 0
cntry1 state1 city2 100 0 0
SUM state1 800 210 0
cntry1 state2 city3 70 0 0
cntry1 state2 city4 180 370 0
SUM state2 250 370 0
SUM cntry1 1050 580 0
cntry2 state3 city5 890 0 0
cntry2 state3 city6 120 420 360
SUM state3 1010 420 360
cntry2 state4 city7 740 0 0
SUM state4 740 0 0
SUM cntry2 1750 420 360
SUM ALL 2800 1000 360
可以使用reindex()方法和自定义排序:
包含小计和^{} 的解决方案。最后一个^{} 和所有} 并添加所有
^{2}$Dataframes
,^{sum
:按注释编辑:
相关问题 更多 >
编程相关推荐