Python error: ValueError: The truth value of a Series is ambiguous

python

#1

Hi,

I’m trying to perform boolean indexing a series using values of other series of same length. This problem can be replicated using the code:

x = pd.Series([1,2,3])
y = pd.Series(x, copy=True)
print y[(x>1) or (x<=1)]

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

If I use simply print x[x>1] it works fine. Not sure why it doesn’t work with the “or” operator.

Please help.

Regards,
Aarshay


#2

Hi @Aarshay,

Boolean indexing in pandas is a little different than normal python indexing.

The correct way to implement it would be;

print y[(x>1) | (x<=1)]

Note: This is for pandas version 18.1, may not be the same in later versions. Check reference here


#3

Thanks @jalFaizy for your response. It works!