mitch
mitch

Reputation: 389

Trying to code a binary variable based on a conditional statement

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

Answers (2)

jezrael
jezrael

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 Falses:

df1['REC30PY'] = df1.velocity<=30

Upvotes: 3

Brad Solomon
Brad Solomon

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

Related Questions