Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to fill missing values in pandas: imputation, removal an

How to fill missing values in pandas: imputation, removal and missing-value indicators

In pandas, missing values show up as NaN, None, NaT or pd.NA, and you handle them with three families of tools: isna() to locate them, dropna() to remove them, and fillna() or scikit-learn imputers to fill them. Choosing between dropping and filling depends on how much of the column is missing and on whether the absence itself carries information — which is where missing-value indicators come in.

Topics: pandas, valores ausentes, imputação

What counts as a missing value in pandas?

pandas represents absence in different ways depending on the column dtype. In float numeric columns the missing value is NaN; in text (object) columns it usually appears as None or NaN; in datetime columns it is NaT; and in the nullable dtypes (Int64, boolean, string) it is pd.NA. Before you fill anything, you need to know which one you are looking at.

The first step is to measure. df.isna() returns a boolean mask with the same shape as the DataFrame, df.isna().sum() counts missing values per column, and df.isna().mean() returns the proportion — the number that actually helps you decide between dropping and imputing.

One detail that slips through: not every absent value is read as null. Strings such as "NA", "N/A" or "-" can arrive as ordinary text. Handle them at read time with pd.read_csv(..., na_values=["NA", "N/A", "-"]) or normalize afterwards with replace.

When should you drop rows or columns with missing values?

dropna() is the fastest option and the most dangerous one. With how='any' (the default) a single null takes down the whole row; with how='all' only fully empty rows are removed. The thresh parameter requires a minimum number of non-null values to keep a row, and subset limits the check to the columns that actually matter.

Dropping makes sense when the missingness is random and hits a small slice of the records, or when the key column of the problem is empty — without it, the row is useless. Leave imputation for systematic missingness: if a specific group simply does not report a given field, deleting those rows removes exactly the group you want to study.

On columns, axis=1 removes whole columns. That is worth it when a column is almost entirely null and is not part of the model, and it is worth little when the column matters and the only problem is filling it in.

How do you fill missing values with fillna?

fillna() accepts a fixed value, a dictionary keyed by column, or a Series aligned by index. For numeric columns, the mean and the median are the standard choices; the median resists outliers better, which matters when the column has a long tail. For categorical columns, the mode or an explicit category such as 'Unknown' works better than any number.

When the column has a natural order — a time series, a sequential measurement — carrying the last valid value forward (df.ffill()) or the next one backward (df.bfill()) preserves continuity better than a global mean. In recent pandas versions, prefer the direct ffill() and bfill() methods, because the method argument of fillna() is deprecated.

A global mean is usually the worst choice when the groups differ. Filling with the median of the group instead of the global median keeps the structure: df['income'] = df.groupby('region')['income'].transform(lambda s: s.fillna(s.median())).

How do you impute without losing information?

Every imputation invents data. The way to avoid losing information is to record that the imputation happened. Create an indicator column before filling: df['income_missing'] = df['income'].isna().astype(int). The model then sees two signals — the estimated value and the fact that the value was missing.

Indicators matter most when the missingness is not random. If high earners skip the income field, the indicator itself carries signal and can help a model more than the imputed value does. The same logic applies to a per-row count of missing fields, df.isna().sum(axis=1), which works as a feature on its own.

Two practical cautions. First, compute the fill value on the training data and apply it to the test data, never the other way around — otherwise the test set leaks into your preprocessing. Second, keep the raw column until you have compared the imputed version against it; if the model does not improve, the imputation was not worth the invented data.

Where do missing values fit in a full data cleaning workflow?

Missing values are one step inside data cleaning and preparation, alongside type conversion, duplicate removal, inconsistent categories and outlier detection. Order matters: fix dtypes and absence codes first, then measure the missingness, then decide per column whether to drop, fill or flag.

A quick triage: df.info() shows dtypes and non-null counts, and df.isna().mean().sort_values(ascending=False) ranks columns by how much is missing, so you can deal with the worst ones first.

If you want to practise this end to end, the Python for Data Science and Analytics course covers Jupyter Notebook setup, NumPy and pandas, data cleaning and preparation, and outlier detection before moving into machine learning — from linear regression and logistic regression to Random Forest, XGBoost and LightGBM — and closes with an end-to-end project. It runs from zero to advanced, needs no prior programming, and includes recorded lessons, guided exercises, a certificate and permanent access. Details are at python.paanalytics.net, with enrollment through the Hotmart checkout by card or boleto; the course is R$ 470, or 12 payments of R$ 20.37 on a card.

StrategyUse it whenWhat you trade off
dropna()Missingness is random and affects a small share of rows, or the key column is emptyLoses rows, and with them any signal the absence carried
fillna() with a statisticThe column matters and only a small share is missingShrinks variance and pulls values toward the centre
ffill() / bfill()The column has a natural order, such as a time series or sequential readingsAssumes the nearest valid value is a better guess than a global one
Group-wise imputationGroups differ in level, such as income by regionMore code, and small groups can produce unstable estimates
Indicator columnMissingness may itself be informativeAdds columns and must be fitted on training data only

Strategies and trade-offs come from the pandas API behaviour described on this page; no product, price or competitor data is involved.

Learn data cleaning with pandas from zero to advanced

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Should I use inplace=True with fillna?

Prefer assignment. inplace=True returns None, which breaks method chaining, and direct assignment — df['col'] = df['col'].fillna(0) — is the style current pandas documentation recommends. It also reads better in a sequence of several cleaning steps.

Does filling with the mean change my data?

Yes. Mean imputation keeps the column mean but shrinks the variance and weakens the correlation with other columns; the median behaves similarly and resists outliers better. If preserving the spread matters, add an indicator column or use a model-based imputer instead of a single statistic.

How do I fill missing dates?

Datetime columns store missing values as NaT. You can fill with a fixed date, df['date'].fillna(pd.Timestamp('2024-01-01')), or propagate neighbours with ffill()/bfill() when the order is meaningful. Filling dates with a mean is not defined, so it is not an option.

Can I fill categorical columns with the mode?

Yes: df['col'].fillna(df['col'].mode()[0]). But when a category is genuinely absent, an explicit label such as 'Unknown' preserves that fact and keeps the category visible in groupby results and plots, instead of hiding it inside the most frequent category.

Should I impute before or after the train/test split?

After. Compute the fill value — mean, median, mode — on the training set and apply it to both sets, otherwise information from the test set leaks into your preprocessing and your evaluation stops being honest. The same rule applies to scikit-learn imputers used inside a Pipeline.

Ler em português →