Examples
import numpy as np
import pandas as pd
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
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, 2, 3, and 4 respectively:
values = {'P': 0, 'Q': 2, 'R': 3, 'S': 4}
df.fillna(value=values)
Only replace the first NaN element:
df.fillna(value=values, limit=1)