2014-10-31 102 views
1

我可以将下列数据框:大熊猫变换数据帧的数据透视表

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 

利用大熊猫透视表:

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

是否有快速创建数据透视表的百分比而不是总数的总和?

+0

是否行总计平均(27537963 + 23448904 + 1213184),第一行,等等?并且您想要将行中的数字替换为百分比? – Jihun 2014-10-31 05:11:42

+0

是的,那正是我想要的。 – user308827 2014-10-31 05:12:24

回答

3

根据意见,我认为你可以做到如下。请注意,我转换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) 
+0

谢谢!这工作。 – user308827 2014-10-31 19:55:14