python - 遍历字典并使用 lambda 函数计算值
问题描述
如果产品线是全局线,我正在尝试迭代并将值与字典中的相应平均值df2
相乘,否则返回值。est7wks
product_mean
forecast
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
。其他部门,如DRINKS
和PHONES
不回来的价值。
解决方案
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
推荐阅读
- reactjs - 为 this.state 分配一个 id 以播放正确的动画?反应原生
- javascript - 从 ApiController 调用 .js 文件中的 JavaScript 函数
- nginx - 无法在一个 Virtualbox 来宾虚拟机上使用 kubernetes master 启动 nginx pod,而在另一台虚拟机上使用 kubernetes 节点
- c# - C# 仅提取最近的压缩文件
- spring-mvc - Spring Boot 发布请求模型验证
- google-cloud-functions - 对 Google 提交审核失败的操作
- java - JAVA - Class 类和 *.class 文件之间的区别?
- git - 重新定位现有的拉取请求以仅显示您的提交
- javascript - await with Promise.all is not in effect
- corda - 3 个参与者与 Corda 之间的交易