You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中计算列/行总计占比(P2P状态分组占比计算)

实现方案

你可以直接基于Pandas的分组聚合+占比计算实现需求,有两种常用实现方式:

方式1:基于你当前已生成的amount_wise_buckets表计算

# 先计算每个金额分箱的总用户数
bucket_total = amount_wise_buckets.groupby('binned_df_pd')['Unique User Id'].transform('sum')
# 计算每个状态的占比,保留2位小数可按需调整
amount_wise_buckets['percentage'] = (amount_wise_buckets['Unique User Id'] / bucket_total * 100).round(2)

# 调整为你需要的输出格式:重复分箱名隐藏、仅展示分箱+状态占比
format_result = amount_wise_buckets[['binned_df_pd', 'P2P_Status', 'percentage']].copy()
format_result.loc[format_result['binned_df_pd'].duplicated(), 'binned_df_pd'] = ''
format_result['percentage'] = '% ' + format_result['percentage'].astype(str)

# 打印结果即可得到你要的样式
print(format_result.to_string(index=False, header=False))

方式2:从原始df直接一步计算(不用先生成中间表)

# 分组计数后直接按分箱维度计算占比,默认生成你需要的层级结构
result = df.groupby(['binned_df_pd', 'P2P_Status'])['Unique User Id'].count()\
           .groupby(level=0).apply(lambda x: round(x / x.sum() * 100, 2))\
           .rename('percentage')
# 打印结果
print(result)

内容的提问来源于stack exchange,提问作者coder_bg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:15:06