日々精進

新しく学んだことを書き留めていきます

pandasで移動平均を計算すると「ValueError: cannot convert to 'float64'-dtype NumPy array with missing values. Specify an appropriate 'na_value' for this dtype.」エラー

以下のようなコードで移動平均を出そうとしたところ、「ValueError: cannot convert to 'float64'-dtype NumPy array with missing values. Specify an appropriate 'na_value' for this dtype.」エラーが発生した。

    return sales.groupby([STORE_ID, ITEM_ID])[SALES_COUNT_LAG_1].rolling(window)\
        .agg(["mean", "max", "min", "std", lambda x: x.mode()[0]]) \
        .reset_index().set_index("seq_idx").drop(columns=[STORE_ID, ITEM_ID]).astype("float32")

原因はdtypeを"Int16"(nullを含めたかったのでintではなくIntにした)にしていたこと。 Int型はnullを表現するためにNATypeというオブジェクトを使うようだが、 Pandasは内部的に集計時にInt型の場合float64に変換して処理するっぽい。 float64はnullをnp.nanで表現するのでNATypeのままでは変換出来ずエラーになる。 しょうが無いので集計対象の列を一時的にfloat64に変換して集計した。

参考:

qiita.com