Examples
import numpy as np
import pandas as pd
df = pd.DataFrame([[np.nan, 2, np.nan, 0],
[3, 4, np.nan, 1],
[5, np.nan, np.nan, 6],
[np.nan, 4, np.nan, 5]],
columns=list('PQRS'))
df
Replace all NaN elements with 0s.
df.fillna(0)
We can also propagate non-null values forward or backward.
df.fillna(method='ffill')
Replace all NaN elements in column ‘P’, ‘Q’, ‘R’, and ‘S’, with 0, 1, 2, and 3 respectively.
values = {'P': 0, 'Q': 1, 'R': 2, 'S': 3}
df.fillna(value=values)
Only replace the first NaN element.
df.fillna(value=values, limit=1)