Valueerror: The Truth Value Of A Series Is Ambiguous
Solution 1:
Assuming we have the following DF:
In[35]: dfOut[35]:
   abc09011774218936754146The following command:
df.a > 5 | df.b > 5
because | has higher precedence (compared to >) as it's specified in the Operator precedence table) it will be translated to:
df.a > (5 | df.b) > 5which will be translated to:
df.a > (5 | df.b) and (5 | df.b) > 5step by step:
In [36]:x=(5|df.b)In [37]:xOut[37]:05172133745Name:c,dtype:int32In [38]:df.a>xOut[38]:0True1False2False3False4Falsedtype:boolIn [39]:x>5Out[39]:0False1True2True3True4FalseName:b,dtype:boolbut the last operation won't work:
In[40]: (df.a > x) and (x > 5)
---------------------------------------------------------------------------
...
skipped
...
ValueError: ThetruthvalueofaSeriesisambiguous. Usea.empty, a.bool(), a.item(), a.any() ora.all().
The error message above might lead inexperienced users to do something like this:
In [12]: (df.a >5).all() | (df.b >5).all()
Out[12]: FalseIn [13]: df[(df.a >5).all() | (df.b >5).all()]
...
skipped
...
KeyError: FalseBut in this case you just need to set your precedence explicitly in order to get expected result:
In[10]: (df.a > 5) | (df.b > 5)
Out[10]:
0True1True2True3True4Falsedtype: boolIn[11]: df[(df.a > 5) | (df.b > 5)]Out[11]:
   abc0901177421893675Solution 2:
This is the real reason for the error:
http://pandas.pydata.org/pandas-docs/stable/gotchas.html
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
>>>if pd.Series([False, True, False]):
     ...
should be. Should it be True because it’s not zero-length? False because there are False values? It is unclear, so instead, pandas raises a ValueError:
>>> if pd.Series([False, True, False]):
    print("I was true")
Traceback
    ...
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
If you see that, you need to explicitly choose what you want to do with it (e.g., use any(), all() or empty). or, you might want to compare if the pandas object is None
Post a Comment for "Valueerror: The Truth Value Of A Series Is Ambiguous"