简体   繁体   English

按行 pivot 表占总数的百分比

[英]Percent of Total by row pivot table

Im am using the following function:我正在使用以下 function:

def pivot_count(df, rows, columns, calc_field):
    df_pivot = df.pivot_table(values=calc_field, 
                              index=rows, 
                              columns=columns, 
                              aggfunc=np.size
                             ).dropna(axis=0, how='all')
    return df_pivot

To create a pivot table with the count of each 'calc_field' to get something like this:要创建一个 pivot 表,其中包含每个“calc_field”的计数,以获得如下信息:

ProfitCluster   Affluent Customer   High Net Worth  Mass Customer
HighMargin             302                324           568
HighRevenue            301                323           645
LessProfitable         246                246           529 

How can i modify the function to get something like this:我怎样才能修改 function 得到这样的东西:

ProfitCluster   Affluent Customer   High Net Worth  Mass Customer
HighMargin             0.25               0.27          0.47
HighRevenue            0.23               0.25          0.50
LessProfitable         0.24               0.24          0.51 

Thanks, SOA community.谢谢,SOA 社区。

Change to crossstab更改为crossstab

def pivot_count(df, rows, columns, calc_field):
    df_pivot = pd.crossstab(values=df[calc_field], 
                              index=df[rows], 
                              columns=df[columns], 
                              normalize='index',
                              aggfunc=np.size
                             )
    return df_pivot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM