19
9

More than 3 years have passed since last update.

Pandas で欠損値を含む整数型を扱う

Posted at

従来、Pandas Series では欠損値を含む整数型は扱うことができなかった。

pd.Series([1, 2, None], dtype=int)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

型を明示せずに欠損値を含む数値データを読み込んだ際は float64 型にキャストされる。

pd.Series([1, 2, None])
0    1.0
1    2.0
2    NaN
dtype: float64

この振る舞いは「numpy.nan は float 型の値だから」という理由に起因するが、我々は欠損値が扱いたいのであって別に numpy.nan である必要はない。

これに対して Pandas v0.24.0 から Nullable integer data type が追加された。 numpy.nan の代わりに新たに pandas.NA を導入することでこの問題に対応したようだ。

pd.Series([1, 2, None], dtype=pd.Int64Dtype())
0       1
1       2
2    <NA>
dtype: Int64

dtype に指定する値は pd.Int64Dtype() の代わりに文字列 "Int64" でも同様に動く。(I が大文字である点に注意。)

また、ドキュメントに

IntegerArray is currently experimental.

と書かれている通り、この機能はまだ実験段階なので利用する際は注意する必要がある。

19
9
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
19
9