Reputation: 389
Having an issue coding up a binary variable based on the code below. I'd like the variable metric
to be 1 if feature
is less or equal to 30 and 0 otherwise. When I run this code I get the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
if df1.Feature <= 30:
df1.metric=1
else:
df1.metric=0
Upvotes: 2
Views: 1967
Reputation: 863351
You can convert boolean mask True
to 1
and False
to 0
by astype
:
df1['REC30PY'] = (df1.velocity<=30).astype(int)
And for True
with False
s:
df1['REC30PY'] = df1.velocity<=30
Upvotes: 3
Reputation: 40918
You are testing the truth value of an entire Series as one object. You can use np.where
instead to test each element. In your case:
df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, 1, 0)
Or, to get booleans:
df1.loc[:, 'REC30PY'] = np.where(df1.velocity<=30, True, False)
Upvotes: 0