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

Pandas中列乘数值:处理不存在列的报错问题

解决透视表缺失列导致的乘法计算报错问题

问题核心

当透视表中缺少预期列(如peach)时,直接通过列名引用会触发KeyError中断计算。可以通过两种方式处理:安全获取列值(不存在则用0替代),或提前补全缺失列并填充0。

方法一:使用.get()安全获取列值

利用DataFrame的.get()方法,当列不存在时返回指定默认值(这里设为0),同时修正原代码中的语法错误(列名多余空格、引号不闭合):

pivot['total'] = (
    pivot.get('Apple', 0).multiply(14) +
    pivot.get('Banana', 0).multiply(110) +
    pivot.get('Mango', 0).multiply(18) +
    pivot.get('grape', 0).multiply(10) +
    pivot.get('peach', 0).multiply(140)
)

方法二:提前补全缺失列(适合多权重场景)

如果需要计算的水果与权重较多,先定义权重字典,遍历补全所有缺失列后再计算,更易维护:

# 定义水果与对应权重的映射
fruit_weights = {
    'Apple': 14,
    'Banana': 110,
    'Mango': 18,
    'grape': 10,
    'peach': 140
}

# 检查并添加缺失列,填充0
for fruit in fruit_weights:
    if fruit not in pivot.columns:
        pivot[fruit] = 0

# 批量计算total
pivot['total'] = sum(pivot[fruit] * weight for fruit, weight in fruit_weights.items())

最终预期结果

执行上述任一方法后,透视表将生成符合要求的total列:

NameAppleBananaMangograpetotal
Jane100014
Celi0100110
Pete001018
Fred000110

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:15:33