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

求助:用Pandas生成客户权重列并计算渠道权重占比

解决步骤与代码实现

1. 准备数据与添加权重列

首先模拟与你需求匹配的Table1数据(和你描述的表格结构一致):

import pandas as pd

# 模拟Table1数据
data = {
    'CustomerID': [1,1,2,3,3,3,4,5,5],
    'Channel': ['Web', 'App', 'Web', 'App', 'Social', 'Web', 'Social', 'Web', 'App'],
    'Visits': [3,2,1,5,1,2,4,2,1]
}
Table1 = pd.DataFrame(data)

推荐实现:向量化计算(Pandas最优方式)

Pandas不推荐手动循环行,用transform可以高效完成每个客户的总访问次数计算,再推导权重:

# 计算每个客户的总访问次数,同步映射到对应行
Table1['TotalVisitsPerCustomer'] = Table1.groupby('CustomerID')['Visits'].transform('sum')

# 计算权重:当前渠道访问数 / 客户总访问数(每个客户权重和为1,5个客户总权重为5)
Table1['weightage'] = Table1['Visits'] / Table1['TotalVisitsPerCustomer']

# 移除临时辅助列(可选)
Table1 = Table1.drop('TotalVisitsPerCustomer', axis=1)

学习用:手动循环实现

如果你需要通过循环理解逻辑,可参考以下代码:

# 初始化权重列
Table1['weightage'] = 0.0

# 遍历每个唯一客户
for customer_id in Table1['CustomerID'].unique():
    # 筛选当前客户的所有记录
    customer_records = Table1[Table1['CustomerID'] == customer_id]
    # 计算该客户的总访问次数
    total_visits = customer_records['Visits'].sum()
    # 为当前客户的各渠道赋值权重
    Table1.loc[Table1['CustomerID'] == customer_id, 'weightage'] = customer_records['Visits'] / total_visits

2. 生成Table2计算渠道权重占比

按渠道分组求和权重,再除以唯一客户数(5)得到占比:

# 按渠道分组,统计权重总和
channel_weight_total = Table1.groupby('Channel')['weightage'].sum()

# 构建Table2
Table2 = pd.DataFrame({
    'Channel': channel_weight_total.index,
    'Weightage_Sum': channel_weight_total.values,
    'Weightage_Percentage': channel_weight_total.values / 5  # 5为唯一客户数量
})

# 重置索引,让Channel作为普通列(可选)
Table2 = Table2.reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:55:18