Passing a scalar value, or a dict mapping column names to different fill values, replaces every NaN with that value directly. The method parameter instead fills gaps using nearby data: forward-fill carries the last valid value forward into subsequent NaN positions, and backward-fill does the reverse, pulling the next valid value backward — both are common for time series data, where the most recent known value is often a reasonable stand-in for a missing one.
1Understanding df.fillna()
Passing a scalar value, or a dict mapping column names to different fill values, replaces every NaN with that value directly. The method parameter instead fills gaps using nearby data: forward-fill carries the last valid value forward into subsequent NaN positions, and backward-fill does the reverse, pulling the next valid value backward — both are common for time series data, where the most recent known value is often a reasonable stand-in for a missing one.
Pass a dict to fillna(), mapping different column names to different fill values, to fill different columns with different, contextually appropriate values in a single call, instead of separate fillna() calls per column.
import pandas as pd
import numpy as np
df = pd.DataFrame({"score": [80, np.nan, 90, np.nan]})
print(df.fillna(0))2Practical Example
Here is a real-world application of df.fillna() showing how it is used in production Pandas code.
import pandas as pd
import numpy as np
df = pd.DataFrame({"temp": [70, np.nan, np.nan, 75]})
print(df.fillna(method="ffill"))3Best Practices
Follow these guidelines when working with df.fillna():
1. Fill numeric columns with a meaningful statistic, like the column's mean or median, rather than an arbitrary placeholder like 0, unless 0 is genuinely meaningful for that column
2. Use forward-fill/backward-fill specifically for time series or ordered data where a nearby value is a reasonable stand-in for a gap
3. Pass a dict to fill different columns with different appropriate values in one call, instead of separate fillna() calls per column
Tip: Pass a dict to fillna(), mapping different column names to different fill values, to fill different columns with different, contextually appropriate values in a single call, instead of separate fillna() calls per column.
import pandas as pd
import numpy as np
df = pd.DataFrame({"score": [80, np.nan, 90, np.nan]})
print(df.fillna(0))