如何处理Pandas透视表:新增累加列并计算层级转化占比?
解决方案
假设你已经生成了透视表table,先移除透视表的All汇总行(如果不需要的话):
# 移除margins生成的All行 table = table.drop('All')
步骤1:计算反向累加值
我们需要从右往左对列进行累加,得到各层级的总用户数:
# 从右到左累加,再反转回原列顺序 cum_table = table.iloc[:, ::-1].cumsum(axis=1).iloc[:, ::-1]
这一步会生成如下累加表:
| Groups | Level 1 | Level 2 | Level 3 |
|---|---|---|---|
| GroupA | 14 | 9 | 3 |
| GroupB | 9 | 6 | 4 |
步骤2:计算转化百分比
基于累加表计算各层级的转化占比,最后格式化为百分比字符串:
# 计算转化占比 conversion = pd.DataFrame() conversion['Level 1'] = '100%' conversion['Level 2'] = (cum_table['Level 2'] / cum_table['Level 1']).apply(lambda x: f"{round(x*100)}%") conversion['Level 3'] = (cum_table['Level 3'] / cum_table['Level 2']).apply(lambda x: f"{round(x*100)}%") # 保持原索引(Groups) conversion.index = table.index
最终得到的结果就是你期望的目标表:
| Groups | Level 1 | Level 2 | Level 3 |
|---|---|---|---|
| GroupA | 100% | 64% | 33% |
| GroupB | 100% | 67% | 67% |
简化版代码
如果想一步完成,可以把逻辑合并:
# 移除All行 table = table.drop('All') # 计算反向累加 cum_table = table.iloc[:, ::-1].cumsum(axis=1).iloc[:, ::-1] # 生成转化表 conversion_table = pd.DataFrame({ 'Level 1': '100%', 'Level 2': (cum_table['Level 2'] / cum_table['Level 1']).map(lambda x: f"{round(x*100)}%"), 'Level 3': (cum_table['Level 3'] / cum_table['Level 2']).map(lambda x: f"{round(x*100)}%") }, index=table.index)
内容的提问来源于stack exchange,提问作者As3adTintin
相关产品推荐
相关产品推荐

