LoginSignup
3
1

More than 3 years have passed since last update.

Pandas : 条件を満たす行を抽出時のエラー ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). の原因と対策

Posted at

結論

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

のエラーの原因として、

複数条件なのにそれぞれを() で括っていない、& | ^などのbit演算ではなくand or notなどと書いているなどが検索で出てきますが1 2

isinin にしてしまっていた時も同様のエラーメッセージがおきるので気をつけましょう。

原因となったコード

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

訂正したコード

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

  1. nkmkさんのブログ記事にこのエラーが起きるケースとその理由(PandasやNumby ndarrayでは曖昧性解消のため、bitwise(&,|,~)を使うとelement-wiseなoperator(and,or,norなど) にoverride されるようになっている)が書かれています https://note.nkmk.me/python-numpy-pandas-value-error-ambiguous/ 

  2.  stackoverflowの記事ではどのように曖昧であるかをもう少し詳しく説明してあります。https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o 

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1