user13412850
user13412850

Reputation: 519

confusion with the use of and operator

below is a simplified version of my dataframe

df = pd.DataFrame(np.random.randint(1,10,(5,2)),columns=['x','y'])

if both x and y values are > 5 then a new column 'z' will have a value of 0 else 1

df[z] = np.where(ddd.x>5 and ddd.y>5,0,1)

however, i get this error

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

get the same even if I use

df[z] = np.where(ddd.x>5 & ddd.y>5,0,1)

what am i missing?

Upvotes: 0

Views: 56

Answers (2)

Saeed
Saeed

Reputation: 4125

You just need to add parenthesis for each condition. Check this out:

df[z] = np.where((ddd.x>5) & (ddd.y>5,0,1))

Upvotes: 0

Mehdi Golzadeh
Mehdi Golzadeh

Reputation: 2583

You need to use parantheses for each condition otherwise it will not work:

df[z] = np.where((ddd.x > 5) & (ddd.y > 5), 0, 1)

Upvotes: 2

Related Questions