我有一个数据帧:
df = pd.DataFrame({"id": [1, 2, 3, 4], "unit_measure": ["pound", "gram", "pound", "gram"], "waste": [10,1000,20,1000]})
id unit_measure waste
1 pound 10
2 gram 1000
3 pound 20
4 gram 1000
我想通过将gram转换为lb来创建一个新列
id unit_measure waste lb_waste
1 pound 10 10
2 gram 1000 2.2
3 pound 20 20
4 gram 1000 2.2
我应用了以下代码:
def lb(df):
if df['unit_measure'] == 'pound':
return df.waste
else:
return df['waste']*0.0022
df['lb_waste'] = df.apply(lb, axis=1)
这给了我以下错误:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
要修复实现,请引用函数参数,而不是全局
df1
。在这里,我将参数名称从df
更改为row
,以更清楚地了解它所代表的内容(@Psidom,我似乎同意这一点):然而,有许多“熊猫”方法比极慢的} 解决方案
apply
方法更有效。例如,@Nk03的^{或通过^{} 的另一个选项:
尝试:
相关问题 更多 >
编程相关推荐