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

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 |

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 : ''(空文字) で穴埋めしてみます。
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 |
NaN ばかり返ってきてしまい、調査したところ欠損値が含まれていたのが原因だった。df.fillna(method='bfill') で一旦対応したので、備忘のために記事にしました。