Ccmmutty logo
Commutty IT
2 min read

Python(pandas) で NaN (欠損値)を置換(穴埋めする)

https://cdn.magicode.io/media/notebox/620f9694-716a-4910-a77d-0949965e0c03.jpeg

サマリー

pandas の fillna を使うと NaN (欠損値) を穴埋めすることができます。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

以下のデータを使っていきます。
python
import numpy as np
import pandas as pd

df = pd.DataFrame({'col_1': [0, 1, 2, np.nan,4],
                   'col_2': ['foo', np.nan,'bar', 'val', np.nan]})
df

col_1 col_2
0 0.0 foo
1 1.0 NaN
2 2.0 bar
3 NaN val
4 4.0 NaN
fillna で穴埋めします。

前(上)の値で穴埋め

python
df.fillna(method='ffill')

col_1 col_2
0 0.0 foo
1 1.0 foo
2 2.0 bar
3 2.0 val
4 4.0 val

後ろ(下)の値で穴埋め

python
df.fillna(method='bfill')

col_1 col_2
0 0.0 foo
1 1.0 bar
2 2.0 bar
3 4.0 val
4 4.0 NaN

ゼロ(特定の値)で穴埋め

python
df.fillna(0)

col_1 col_2
0 0.0 foo
1 1.0 0
2 2.0 bar
3 0.0 val
4 4.0 0
文字列のカラムもゼロ埋めするのは違和感ありますね。。。

列ごとに特定の値で穴埋め

各列で NaN を、col_1 : 0, col_2 : ''(空文字) で穴埋めしてみます。
python
df.fillna({'col_1': 0, 'col_2': ''})

col_1 col_2
0 0.0 foo
1 1.0
2 2.0 bar
3 0.0 val
4 4.0

メモ

以前の記事(Python(TA-Lib)で株価のテクニカル分析(その1) 移動平均やインジケーター(MACD)を算出する) の様に移動平均などを算出した際に返り値が NaN ばかり返ってきてしまい、調査したところ欠損値が含まれていたのが原因だった。
df.fillna(method='bfill') で一旦対応したので、備忘のために記事にしました。

Discussion

コメントにはログインが必要です。