[英]Percent of Total by row pivot table
我正在使用以下 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
要创建一个 pivot 表,其中包含每个“calc_field”的计数,以获得如下信息:
ProfitCluster Affluent Customer High Net Worth Mass Customer
HighMargin 302 324 568
HighRevenue 301 323 645
LessProfitable 246 246 529
我怎样才能修改 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
谢谢,SOA 社区。
更改为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.