環境
- 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''