

numpy.isnan() したら TypeError になった…Pythonで配列データを数値計算するのによく使われる NumPy 。
配列データを扱う様々な関数が用意されていて便利である。
そんな NumPy の持つ機能の一つに isnan() がある。
isnan()は名前の通り、値が nan であるか判定する機能だ。
それを使った際にこんなエラーが出てしまうことがある。
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''
何故 TypeError が発生するのか。
そこで今回はnumpy.isnanでTypeError: ufunc 'isnan' not supportedになる原因について紹介する。
この記事を書いている人

記事を読むメリット
numpy.isnanでTypeError: ufunc 'isnan' not supportedになる原因がわかり、nan判定で失敗しなくなる
データ準備

まずはnanを含むデータを準備する。
以下の内容のCSVを isnan_sample.csv として保存する。
isnan_sample.csv
"a",12,100
"b",,105
,12,90
"d",13,85
そしてpandas.DataFrameとして読み込む。
DATA
import pandas as pd
import numpy as np
df1 = pd.read_csv("isnan_sample.csv")
print(df1)
# id age score
# 0 a 12.0 100
# 1 b NaN 105
# 2 NaN 12.0 90
# 3 d 13.0 85
このデータを使って解説していく。
numpy.isnanでnanを判定する

まず numpy.isnan() をするとnanを判定できる。
SAMPLE
print(df1["id"].loc[2]) # nan print(np.isnan(df1["id"].loc[2])) # True
0行目から数えて2行目はid列の中身が nan である。
それを isnan() で判定すると True が返される。
他の行にnumpy.isnanを用いるとエラーになる

numpy.isnan() をするとnanを判定できるが、nanではない行に使うと何故かエラーになってしまう。
SAMPLE
for idx, row in df1.iterrows():
print(row["id"])
# a
# b
# nan
# d
for idx, row in df1.iterrows():
print(np.isnan(row["id"]))
# 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''
numpy.isnanでTypeError: ufunc 'isnan' not supportedになる原因

何故 numpy.isnan() で TypeError: ufunc 'isnan' not supported になってしまったのか。
原因は文字列。
確認のために、数値とnanが含まれる列に isnan() を使ってみる。
SAMPLE
for idx, row in df1.iterrows():
print(row["age"])
# 12.0
# nan
# 12.0
# 13.0
for idx, row in df1.iterrows():
print(np.isnan(row["age"]))
# False
# True
# False
# False
このように数値と nan が入っているage列に対して isnan() してもエラーにはならない。
つまり文字列が入っている列には isnan() は使えないということになる。


pandasでnan判定するにはisnaを使用

pandasでnan判定するには numpy.isnan() ではなく、pandas.isna() を使用する。
使い方としては以下の通り。
SAMPLE
for idx, row in df1.iterrows():
print(row["id"])
# a
# b
# nan
# d
for idx, row in df1.iterrows():
print(pd.isna(row["id"]))
# False
# False
# True
# False
numpy.isnan() では文字列を判定させるとエラーになっていたが、 pandas.isna() では正しくTrue/False判定ができているのがわかる。
まとめ

今回はnumpy.isnanでTypeError: ufunc 'isnan' not supportedになる原因について解説した。
numpy.isnan() でエラーになるポイントは以下の通り。
ココがポイント
numpy.isnan()でTypeErrorになるのは文字列をnan判定させたから- 代わりに
pandas.isna()を使えば文字列でも正しくnan判定できる
他にもPython関連の記事もあるので、もし興味があれば見ていって欲しい。



