首页 > 解决方案 > 遍历字典并使用 lambda 函数计算值

问题描述

如果产品线是全局线,我正在尝试迭代并将值与字典中的相应平均值df2相乘,否则返回值。est7wksproduct_meanforecast

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
)

它有效,但只返回字典 item 中第一个变量GROCERY。其他部门,如DRINKSPHONES不回来的价值。

标签: pythonpandasdataframelambda

解决方案


section_dep功能应该是:

def section_dep(product_mean, department, est_7wks, Product_Line, forecast):
    if Product_Line == 'Global-Line-Line' and department in product_mean:
        return est_7wks * product_mean[department]
    else:
        return forecast

推荐阅读