ValueError: The truth value of a Series is ambiguous - Pandas querying

Can someone please explain the error in the code (Reference Week 10 pandas - topic - Querying from dataframe)

This will not work.
df['method'] in ['Radial Velocity', 'Transit']

is it beacuse it just returns a single value true or false and not the indices of the rows as to where it is true and where it is false, for the df command to print the respective rows?

Yes, I think so after you add ‘any’ or ‘all’ to it.

For similar reason ‘&’ and ‘|’ was used (instead of ‘and’ and ‘or’).

Check this thread.

1 Like

Understood, Thank you :grin:

The expression you used for checking ‘method’ looks very logical. I wish it was valid :slightly_smiling_face:

1 Like

Pressed F,
I wished that too :sweat_smile:

Pandas follows the numpy convention of raising an error when you try to convert something to a bool. This happens in a if or when using the boolean operations, and, or, or not. It is not clear what the result of.

example

5 == pd.Series([12,2,5,10])

The result you get is a Series of booleans, equal in size to the pd.Series in the right hand side of the expression. So, you get an error. The problem here is that you are comparing a pd.Series with a value, so you’ll have multiple True and multiple False values, as in the case above. This of course is ambiguous, since the condition is neither True or False. You need to further aggregate the result so that a single boolean value results from the operation. For that you’ll have to use either any or all depending on whether you want at least one (any) or all values to satisfy the condition.

(5 == pd.Series([12,2,5,10])).all()

# False

or

(5 == pd.Series([12,2,5,10])).any()

# True