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

Pandas Series如何计算商品组合内各条目的加权平均分值

Pandas实现Bundle条目加权分值计算方案

实现思路

  • 第一步:将Bundle列的列表结构展开,每个元素单独成一行,同步保留对应行的Price值
  • 第二步:按拆分后的单个条目分组,分别统计对应Price总和、条目出现的Bundle总数,计算得出加权分值(总和/总数)
  • 第三步:按要求格式化输出结果

完整可运行代码

import pandas as pd

# 构造示例源数据,实际使用时替换为自己的数据源即可
df = pd.DataFrame({
    'Bundle': [['A', 'C', 'B'], ['A', 'B', 'C', 'D'], ['B']],
    'Price': [10, 20, 30]
})
# 提前存储价格字符串,方便后续输出计算过程
df['price_str'] = df['Price'].astype(str)

# 1. 展开Bundle列,每个元素单独成一行
exploded_df = df.explode('Bundle', ignore_index=True)

# 2. 分组聚合计算所需指标
result = exploded_df.groupby('Bundle').agg(
    总价=('Price', 'sum'),
    出现次数=('Price', 'count'),
    价格列表=('price_str', '+'.join)
).reset_index()
result['分值'] = result['总价'] / result['出现次数']

# 3. 按要求格式化输出
for _, row in result.iterrows():
    if row['出现次数'] > 1:
        print(f"{row['Bundle']} = {int(row['分值'])} (({row['价格列表']})/{row['出现次数']})")
    else:
        print(f"{row['Bundle']} = {int(row['分值'])}")

输出结果

运行上述代码后输出内容完全匹配预期:

A = 15 ((10+20)/2)
B = 20 ((10+20+30)/3)
C = 15 ((10+20)/2)
D = 20

注意事项

  • explode方法需要Pandas 0.25及以上版本支持,版本过低可以先执行pip install --upgrade pandas升级
  • 代码逻辑完全贴合计算规则,不需要修改即可适配其他同结构的源数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:54:05