首页 > 解决方案 > 使用 lambda 函数应用嵌套字典迭代

问题描述

我有一个嵌套字典

product_mean = {'diamond_sec': {'CONFECTIONARIES': 1.94, 'CARBONATED DRINKS': 1.57,'APPLE LAPTOPS': 2.08}, {'global_sec':{'CONFECTIONARIES': 1.13,'CARBONATED DRINKS': 1.11, 'APPLE LAPTOPS': 1.19,}, 'diamond_dep': {GROCERY: 1.72,'LAPTOP': 1.71,'ACCESORIES': 1.67,'PHONES': 1.79}, {'global_dep':{'GROCERY': 1.18,'LAPTOP ACCESORIES': 1.20,'PHONES': 1.21,}}

嵌套字典包含 4 类值的值 1) diamond_sec,菱形线的平均截面平均值 2) global_sec 非菱形线的平均截面值 3) diamond_dep 是菱形线的平均部门平均值,4) global_dep 是非菱形线的平均部门平均值

数据框

df2 = pd.DataFrame([
{'Description':'cornflakes', 'department':'GROCERY',
    'section':'CONFECTIONARIES', 'h_wksale':403.0,
    'est_7wks':2043,
    'Product_Line':'Diamond-Line', 'forecast':'pending'}, {'Description':'coca-cola', 'department':'DRINKS',
    'section':'CARBONATED DRINKS', 'h_wksale':1500.0,
    'est_7wks':10500,
    'Product_Line':'Global-Line-Line', 'forecast':'pending'}, {'Description':'iphone 11', 'department':'PHONES',
    'section':' ', 'h_wksale':20.0,
    'est_7wks':140,
    'Product_Line':'Diamond-Line', 'forecast':'pending'}, {'Description':'Tin Milk', 'department':'GROCERY',
    'section':' ', 'h_wksale':5.0,
    'est_7wks':35,
    'Product_Line':'Silver-Line', 'forecast':'pending'}])

产品菱形和全球线具有其自己计算的各个部门和部门的平均值。

更准确的平均值是“部分”平均值,所有产品都有一个“部门”变量值,但并非所有产品都有一个“部分”变量值。

因此,对于那些在字典中具有截面平均值的人,我需要将产品“est7wks”值乘以字典中相应的平均值,而对于那些没有“截面值”的人,我需要将 est7wks 值与相应的值相乘字典中的“部门”平均值。

请注意,如果产品线是菱形线,则“est7wks”将乘以字典中“菱形线”的相应部分平均值,但如果该部分是变量值缺失,则让部门平均值用于相乘'est7wks' 代替。全球线也是如此

我的代码。

def diamond_rank(product_mean, Product_Line, section, forecast):
    for k,v in product_mean.items():
        for key, value in v.items():
            if Product_Line =='Diamond-Line' and department == k:
             return est_7wks*value
            if Product_Line !='Diamond-Line' and department == k:
             return est_7wks*value
            if Product_Line =='Diamond-Line' and section == k:
             return est_7wks*v
            if Product_Line !='Diamond-Line' and section == k:
             return est_7wks*v
        else:
         return forecast

df['forecast'] = df.apply(lambda x:diamond_rank(department_mean_d, x['Product_Line'],x['section'],x['est_7wks'],x['forecast']),axis=1)

结果应该是这样的。

df2 = pd.DataFrame([
{'Description':'cornflakes', 'department':'GROCERY',
    'section':'CONFECTIONARIES', 'h_wksale':403.0,
    'est_7wks':'2043',
    'Product_Line':'Diamond-Line', 'forecast':3963.42}, {'Description':'coca-cola', 'department':'DRINKS',
    'section':'CARBONATED DRINKS', 'h_wksale':1500.0,
    'est_7wks':'10500',
    'Product_Line':'Diamond-Line', 'forecast':16485}, {'Description':'iphone 11', 'department':'PHONES', 'section':' ', 'h_wksale':20.0, 'est_7wks':'140','Product_Line':'Global-Line', 'forecast':169.4}, {'Description':'Tin Milk', 'department':'GROCERY',
    'section':' ', 'h_wksale':5.0,
    'est_7wks':'35',
    'Product_Line':'Silver-Line', 'forecast':41.3}])

标签: pythonpython-3.x

解决方案


推荐阅读