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

遍历DataFrame结合字典计算值时仅首个字典项生效问题

问题排查与解决:DataFrame批量计算逻辑错误

需求说明

遍历df2数据框,执行以下逻辑:

  • 若Product_Line为Global-Line,将est_7wks的值与product_mean字典中对应department的均值相乘,作为新的forecast值
  • 否则直接保留原forecast值

给定数据

import pandas as pd

product_mean = { 'GROCERY': 1.94, 'DRINKS': 1.57, 'PHONES': 2.08 }
df2 = pd.DataFrame([
    { 'Description': 'cornflakes', 'department': 'GROCERY', 'est_7wks': 2043, 'Product_Line': 'Global-Line', 'forecast': 'pending' },
    { 'Description': 'coca-cola', 'department': 'DRINKS', 'est_7wks': 10500, 'Product_Line': 'Global-Line', 'forecast': 'pending' },
    { 'Description': 'iphone 11', 'department': 'PHONES', 'est_7wks': 140, 'Product_Line': 'Diamond-Line', 'forecast': 'pending' }
])

用户原有代码

def section_dep(product_mean, department, est_7wks, Product_Line, forecast):
    for k,v in product_mean.items():
        if department == k and Product_Line = 'Diamond-Line':
            return est_7wks*v
        else:
            return forecast
df['forecast'] = df.apply(
    lambda x: section_dep( product_mean, x['department'], x['est_7wks'], x['Product_Line'], x['forecast'] ),
    axis=1
)

问题描述

运行上述代码后,仅字典中第一个项GROCERY对应的行能返回正确计算值,DRINKS和PHONES的行无法得到预期结果,始终返回pending。

错误原因分析

咱们来拆解下问题出在哪:

  1. 循环逻辑错误:函数里的for循环第一次迭代就直接return了,不管当前department是否匹配。比如处理DRINKS行时,第一次循环取到k=GROCERY,不匹配就直接返回forecast,根本不会继续检查DRINKS这个键。
  2. 条件完全写反+语法错误:需求是Product_Line为Global-Line时计算,但你代码里写的是Product_Line = 'Diamond-Line'——这里不仅逻辑反了,还把比较运算符==写成了赋值运算符=,这会直接导致语法错误。
  3. 变量名不一致:你用df.apply但给定的数据框是df2,运行时会抛出NameError,找不到df这个变量。

修正后的代码

我们可以简化逻辑,不用遍历字典(直接通过键取值更高效),同时修正所有错误:

def section_dep(product_mean, department, est_7wks, product_line, forecast):
    # 先判断是否符合计算条件:Product_Line是Global-Line,且department在字典中有对应值
    if product_line == 'Global-Line' and department in product_mean:
        return est_7wks * product_mean[department]
    # 不符合条件则返回原forecast值
    return forecast

# 注意变量名是df2,不是df
df2['forecast'] = df2.apply(
    lambda x: section_dep(
        product_mean, 
        x['department'], 
        x['est_7wks'], 
        x['Product_Line'], 
        x['forecast']
    ),
    axis=1
)

验证结果

运行修正后的代码后,df2的结果如下:

print(df2)
# 输出:
#     Description department  est_7wks   Product_Line   forecast
# 0    cornflakes     GROCERY      2043  Global-Line   3963.42
# 1     coca-cola      DRINKS     10500  Global-Line  16485.00
# 2    iphone 11       PHONES       140  Diamond-Line    pending

可以看到:

  • 前两行Global-Line的行都正确完成了乘法计算
  • 第三行Diamond-Line的行保留了原forecast值,完全符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:27:31