0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

`if numpy.isnan(pandas.NA)`で"boolean value of NA is ambiguous"というTypeErrorが発生した

Last updated at Posted at 2024-02-14

環境

  • Python 3.12.1
  • pandas 2.2.0
  • numpy 1.26.4

何が起きたのか

if numpy.isnan(pandas.NA): passを実行したら、"boolean value of NA is ambiguous"というTypeErrorが発生しました。

In [52]: if numpy.isnan(pandas.NA):
    ...:     pass
    ...:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[52], line 1
----> 1 if numpy.isnan(pandas.NA):
      2     pass

File missing.pyx:392, in pandas._libs.missing.NAType.__bool__()

TypeError: boolean value of NA is ambiguous

原因

numpy.isnan(pandas.NA)の結果はpandas.NAです。pandas.NAに対してbool値に変換しようとしたので、TypeErrorが発生しました。

In [51]: a = numpy.isnan(pandas.NA)

In [52]: if a: pass
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[52], line 1
----> 1 if a: pass

File missing.pyx:392, in pandas._libs.missing.NAType.__bool__()

TypeError: boolean value of NA is ambiguous

Since the actual value of an NA is unknown, it is ambiguous to convert NA to a boolean value.1

補足:少しハマったこと

numpy.isnan()という名前から、「numpy.isnan()にスカラー値を渡したらTrueかFalseを返すのだ」と、私は思っていたので、このエラー解決するのに少し時間がかかりました。

pandasは、numpyのufuncではpandas.NAを返すように実装しています。

pandas.NA implements NumPy’s __array_ufunc__ protocol. Most ufuncs work with NA, and generally return NA 2

numpy.isnan()もufuncです。したがって、numpy.isnan(pandas.NA)はbool値でなくpandas.NAを返すようです。

補足:numpy.isnanにarrayを渡したときの振る舞い


In [143]: d = numpy.array([1.1, pandas.NA, 3.3])

In [144]: d
Out[144]: array([1.1, <NA>, 3.3], dtype=object)

In [145]: numpy.isnan(d)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[145], line 1
----> 1 numpy.isnan(d)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
  1. https://pandas.pydata.org/docs/user_guide/missing_data.html#na-in-a-boolean-context

  2. https://pandas.pydata.org/docs/user_guide/missing_data.html#numpy-ufuncs

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?