1
votes

When I run the following code:

if df.loc[df['state_code'].isin(['12','09'])]:

It gives this error:

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

What is wrong here?

1
Can you provide your dataframe? I suspect that isin might return True on some columns but False on other columns.MooingRawr
This is not a pure python exception. Please tell us about your environment. And it would be helpful to describe what df is.Simon

1 Answers

4
votes

The issue tells you that the Series returned by your operation holds no intrinsic truth value. Indeed, the operation will always return something and you have to chose what you actually want:

  • if any of the returned values is true, meaning there exists an element in df which is in ['12','09']
  • if all of the returned values are true, meaning all elements in df are in ['12','09']
  • if the returned Series contains any element, meaning not empty

So:

if not df.loc[df['state_code'].isin(['12','09'])].empty:

or

if df.loc[df['state_code'].isin(['12','09'])].any():

or

if df.loc[df['state_code'].isin(['12','09'])].all():

Check out the documentation

For more help, provide a minimal working example of your code