user3294779 user3294779 - 1 year ago 72
Python Question

Conditionally update Data Frame column

I'm trying to update a column from a value of 0 to a value of 1 if certain conditions are true. Here is my code:

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

This is the error I'm getting:

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

Does anybody have any ideas of what's going on here?

Answer Source

When doing boolean indexing you need to use the logical operator for and which is &. See the doc here for more info

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

Basically just your answer with & instead of and. I just rewrote it to make it a little clearer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download