有条件地更新数据框列

时间:2016-10-11 02:20:06

标签: python pandas

如果某些条件为真,我尝试将列从值0更新为值1。这是我的代码:

df_['win'] = 0
df_.loc[df_['predicted_spread'] > df_['vegas_spread'] and df_['actual_spread'] > df_['vegas_spread'], 'win'] = 1

这是我得到的错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

有没有人对这里发生了什么有任何想法?

2 个答案:

答案 0 :(得分:1)

尝试

df_['win'] = 0
df_.loc[df_['predicted_spread'].gt(df_['vegas_spread']) and df_['actual_spread'].gt(df_['vegas_spread']), 'win'] = 1

答案 1 :(得分:1)

在进行布尔索引时,您需要使用and的{​​{1}}逻辑运算符。有关详细信息,请参阅文档here

&

基本上只有df['win'] = 0 cond_1 = df['predicted_spread'] > df['vegas_spread'] cond_2 = df['actual_spread'] > df['vegas_spread'] df.loc[cond_1 & cond_2, 'win'] = 1 代替&的答案。我只是重写了它,使它更清晰。