Craig
Craig

Reputation: 1985

ValueError: The truth value of a Series is ambiguous.

I've seen a few posts with this error but they don't apply to this particular situation.

Say my dataframe is as follows...

import pandas as pd
df = pd.DataFrame(np.random.randint(0,20,size=(10, 2)), columns=list('AB'))


    A   B
0  12  12
1  15   3
2   3  12
3   4  11
4  12   9
5   0   4
6  19  12
7   5  19
8  11  16
9  13   8

I want to create a column factor which depends on the value of column A. Let's say if df[A]<=10 then factor=5 else factor=8

I tried:

df['factor'] = 5 if df['A'] <= 10 else 8

But I get an error:

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

Upvotes: 0

Views: 2014

Answers (1)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

You need this:

df['factor'] = np.where( df.A <= 10, 5, 8) 

You can also use a mask

mask = df['A'] <= 10 
df['factor'] = 8 
df.loc[mask, 'factor'] = 5 

Note: the answer in Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() explains neatly the reason behind the error.

Upvotes: 2

Related Questions