pandas 转换数据框数据透视表 [英] pandas transform dataframe pivot table
本文介绍了 pandas 转换数据框数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以变换以下数据框:
I can transform the following dataframe:
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
通过使用熊猫数据透视表:
by using pandas pivot table:
plot_table = LCC_PI_df.pivot_table(index=['RECL_LCC'], columns='RECL_PI', values='COUNT', aggfunc='sum')
有没有一种快速的方法来创建数据透视表,该数据透视表使用行总数的百分比而不是原始计数的总和?
Is there a quick way to create the pivot table with percentage of row totals instead of raw sum of counts?
推荐答案
根据评论,我认为您可以按照以下步骤进行操作.请注意,我将COUNT列转换为整数以完成此操作:
According to comments, I think you can do that like following. Note that I converted the COUNT column to integers to do this :
#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)
这篇关于 pandas 转换数据框数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文