pandas transform dataframe pivot选项卡

2024-06-28 20:01:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以转换以下数据帧:

   VALUE       COUNT  RECL_LCC  RECL_PI
0      1  15,686,114         3        1
1      2  27,537,963         1        1
2      3  23,448,904         1        2
3      4   1,213,184         1        3
4      5  14,185,448         3        2
5      6  13,064,600         3        3
6      7  27,043,180         2        2
7      8  11,732,405         2        1
8      9  14,773,871         2        3

像这样:

^{pr2}$

通过使用pandas pivot表:

plot_table = LCC_PI_df.pivot_table(index=['RECL_LCC'], columns='RECL_PI', values='COUNT', aggfunc='sum')

有没有一种快速的方法来创建包含行总数百分比而不是原始计数总和的透视表?在


Tags: columns数据pandasdfindexplotvaluecount
1条回答
网友
1楼 · 发布于 2024-06-28 20:01:44

根据评论,我认为你可以像下面这样做。请注意,我将COUNT列转换为整数来执行此操作:

#convert strings of the COUNT column to integers
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) 
LCC_PI_df.COUNT = LCC_PI_df.COUNT.apply(locale.atoi)

plot_table = LCC_PI_df.pivot_table(index=['RECL_LCC'], columns='RECL_PI', values='COUNT', aggfunc='sum')
#Calculate percentages
plot_table = plot_table.apply(lambda x : x / x.sum(), axis=1)   

相关问题 更多 >