gpt4 book ai didi

python - pandas 转换数据框数据透视表

转载 作者:行者123 更新时间:2023-11-30 23:18:32 27 4
gpt4 key购买 nike

我可以转换以下数据框:

   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

变成这样的东西:

RECL_PI            1           2           3
RECL_LCC
1 27,537,963 23,448,904 1,213,184
2 11,732,405 27,043,180 14,773,871
3 15,686,114 14,185,448 13,064,600

通过使用 pandas 数据透视表:

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

是否有一种快速方法可以使用行总数百分比而不是原始计数总和来创建数据透视表?

最佳答案

根据评论,我认为你可以像下面这样做。请注意,我将 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)

关于python - pandas 转换数据框数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667524/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com