
Pandasで読み込んだデータの小数点を整数に修正できない……
CSVをpandasで読み取った際に、
自動的に少数点ありの数値に変換されてしまうケースがあります。
そんなときの簡単な対処法をお伝えしていきます。
目次
【エラー内容】IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer
今回はposデータのcustomer_codeに関わる不具合です。
pandasで通常通り、csvを読み込みます。
pos_master = pd.read_csv("pos.csv")
pos_master['customer_code'].head()
しかし、下記の通り、本来、int型だった顧客コードが float型に勝手に変換されてしまっています。


astypeで変換するもエラーが発生
検索ででてくる一般的な解決方法に基づいて、以下のコマンドを実行しました。
pos_master['customer_code'] = pos_master['customer_code'].astype(int)
しかし、以下のエラーが発生してしまいました。
IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer
IntCastingNaNErrorの解決方法
上記のようなエラーが発生した場合には、
簡単に解決できる方法があります。
csvを読み込む際に、object型に変換してしまうだけです。
手順は以下の通り、引数にdtype=objectを追記するだけです。
pos_master = pd.read_csv("pos.csv",dtype=object)
pos_master['customer_code'].head()
実行結果は以下です。





やった!顧客コードのfloat型が修正できた
まとめ
IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer
今回はastypeで変換を試みた際に、上記のエラーが発生した際に、
簡単に解決できる手順をご紹介しました。
簡易的な方法ですが、ぜひ参考にしてみてください。