Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame([[np.nan, 3, np.nan, 0],
                   [4, 5, np.nan, 2],
                   [np.nan, np.nan, np.nan, 6],
                   [np.nan, 4, np.nan, 5]],
                  columns=list('PQRS'))
df
Out[2]:
P Q R S
0 NaN 3.0 NaN 0
1 4.0 5.0 NaN 2
2 NaN NaN NaN 6
3 NaN 4.0 NaN 5

Replace all NaN elements with 0s:

In [3]:
df.fillna(0)
Out[3]:
P Q R S
0 0.0 3.0 0.0 0
1 4.0 5.0 0.0 2
2 0.0 0.0 0.0 6
3 0.0 4.0 0.0 5

We can also propagate non-null values forward or backward:

In [4]:
df.fillna(method='ffill')
Out[4]:
P Q R S
0 NaN 3.0 NaN 0
1 4.0 5.0 NaN 2
2 4.0 5.0 NaN 6
3 4.0 4.0 NaN 5

Replace all NaN elements in column ‘P’, ‘Q’, ‘R’, and ‘S’, with 0, 2, 3, and 4 respectively:

In [5]:
values = {'P': 0, 'Q': 2, 'R': 3, 'S': 4}
df.fillna(value=values)
Out[5]:
P Q R S
0 0.0 3.0 3.0 0
1 4.0 5.0 3.0 2
2 0.0 2.0 3.0 6
3 0.0 4.0 3.0 5

Only replace the first NaN element:

In [6]:
df.fillna(value=values, limit=1)
Out[6]:
P Q R S
0 0.0 3.0 3.0 0
1 4.0 5.0 NaN 2
2 NaN 2.0 NaN 6
3 NaN 4.0 NaN 5