[PYTHON] Pandas: Error when extracting rows that meet the conditions ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool (), a.item (), a.any () or a.all () Causes and countermeasures

Conclusion

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

As the cause of the error

Although there are multiple conditions, each is not enclosed in (), and it is written as ʻand or notinstead of bit operations such as& | ^`, but [^ 1] [^ stackoverflow] Article]

If you change ʻisin to ʻin, you will get the same error message, so be careful.

The code that caused it

error.py


tmp__ = transactions[(transactions["year"] == "2014" ) & (transactions ["month"] in ["06","07","08"]))]

Corrected code

correct.py


tmp__ = transactions[(transactions["year"] == "2014" ) & (transactions["month"].isin( ["06","07","08"]))]

[^ 1]: Cases and reasons why this error occurs in nkmk's blog post (Pandas and Numby ndarray are element-wise operators (and,) using bitwise (&, |, ~) to disambiguate. (Or, nor, etc.) is overridden) is written https://note.nkmk.me/python-numpy-pandas-value-error-ambiguous/

[^ stackoverflow article]: The stackoverflow article explains in a little more detail how ambiguous it is. https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o

Recommended Posts

Pandas: Error when extracting rows that meet the conditions ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool (), a.item (), a.any () or a.all () Causes and countermeasures