# Imputing missing data in Python

Learn how to fill missing values in datasets with Python. Covers pandas fillna, SimpleImputer, KNNImputer, and IterativeImputer with code examples.

[Imputing missing data](/articles/missing-data-imputation-methods-an-overview/) in Python means replacing absent values with substituted ones so your dataset can be used in analysis or machine learning. Python offers simple techniques like filling with the mean or median, and advanced ones like KNN and iterative imputation. This guide shows when to use each method and how to apply them. 

- Use pandas fillna for quick, simple missing value replacement.
- SimpleImputer from scikit-learn works in machine learning pipelines.
- KNNImputer uses similar rows to estimate missing numbers.
- IterativeImputer models each feature to fill gaps more accurately.
 

## What is missing data imputation 

Missing data imputation is the process of filling absent values in a dataset. A dataset may have blanks because of entry errors, sensor failures, or survey non-responses. Many Python machine learning tools cannot process missing values. Imputation lets you keep rows that would otherwise be discarded. 

Simply deleting rows with missing values can cause bias. If missingness is not random, deletion distorts the dataset. Imputation preserves the sample size and the relationships between variables. The choice of method affects the results of later analysis. 

Python supports both basic and sophisticated imputation techniques. Basic methods replace missing values with a single number like the mean. Advanced methods estimate values from the other data points. The right technique depends on the amount of missing data and the analysis goal. 

## Quick imputation with pandas fillna 

The pandas library provides the fillna method to replace missing values directly. For example, data['column'].fillna(0) fills every blank with zero. You can also use the column mean or median as the replacement. This is the simplest way for small datasets and quick checks. 

fillna works on a whole DataFrame as well. You can apply one value to every column or a dictionary of values per column. The method also has the method='ffill' option for forward filling. Forward filling copies the last known value into the next blank. 

Pandas fillna is powerful but not integrated into scikit-learn pipelines. If you need imputation as part of model training, use a scikit-learn imputer. For one-off analyses and data cleaning, fillna is fast and easy to read. It suits tasks where you know the correct fill value. 

- Fill with a constant: data.fillna(0)
- Fill with column mean: data['x'].fillna(data['x'].mean())
- Fill forward: data.fillna(method='ffill')
- Fill backward: data.fillna(method='bfill')
 

## SimpleImputer for basic strategies 

The SimpleImputer class from scikit-learn applies a chosen strategy to each column. Common strategies include replacing missing values with the mean, median, or a constant. SimpleImputer works on numeric and categorical data. It can be part of a machine learning pipeline to avoid data leakage. 

To use SimpleImputer, you specify a strategy and fit the imputer on the training data. The imputer learns the mean or median from the training set. Then you transform both training and test sets with the same imputer. This ensures the test data does not influence the fill values. 

Mean and median imputation are simple but can distort variable distributions. They reduce the variance of a column and change its correlation with other columns. For a quick baseline model, these methods are acceptable. More advanced methods preserve the data structure better. 

## KNNImputer for local similarity 

KNNImputer fills missing values using the k-nearest neighbors algorithm. For each row with a missing value, it finds the k rows most similar in the observed features. The missing value is then estimated from these neighbors. This method captures local patterns that mean imputation misses. 

KNNImputer works best for continuous numeric variables. It is sensitive to feature scaling, so you should standardize columns first. The number of neighbors k is a tuning parameter. A smaller k adapts to local structure, while a larger k smooths the estimates. 

KNN imputation can be slow on large datasets. Each prediction requires computing distances to many rows. However, for moderate-sized datasets it gives better predictions than simple measures. KNNImputer is available in scikit-learn and follows the same fit-transform interface. 

## IterativeImputer for multivariate modeling 

IterativeImputer models each feature with missing values as a function of other features. It starts with an initial guess, often the column mean. Then it cycles through the columns and predicts missing values using a regression model. Several iterations refine the estimates until convergence. 

The default estimator for IterativeImputer is BayesianRidge regression. You can change the estimator to any regressor from scikit-learn. The imputer works well when features are correlated. It can produce more realistic values than univariate methods. 

Iterative imputation is computationally intensive. It fits many models and may not scale to very large data. It is a strong choice for datasets with moderate missingness and clear relationships among variables. Always validate the imputation by comparing model performance after imputation. 

## When to choose each imputation method 

The right imputation method depends on the missing data pattern and your analysis goals. Start with simple methods like mean or median for a quick solution. If data is missing completely at random, simple methods work reasonably well. When missingness is related to other variables, advanced methods help more. 

For a small amount of missing data, pandas fillna with a sensible constant is efficient. In a machine learning pipeline, use SimpleImputer for simplicity. KNNImputer suits medium-sized numerical datasets with local structure. IterativeImputer is ideal for datasets with complex feature relationships. 

Evaluate imputation by comparing the downstream model or analysis results. Try several methods and check which yields the best performance. Keep in mind that imputation introduces uncertainty. You may also consider recording which values were imputed for later analysis. 
| Method | Best suited for | Speed on large data | 
| Pandas fillna | Quick manual fills, one-off scripts | Fast | 
| SimpleImputer | Baseline pipelines, simple strategies | Fast | 
| KNNImputer | Numerical data with local similarity | Slow | 
| IterativeImputer | Correlated features, complex data | Slowest |  

## Handling missing values before imputation 

Before imputing, examine the extent of missingness in each column. A column with more than half its values missing may carry little information. In such a case, dropping the column could be better than imputing. Visual tools like missingno or a simple count help you decide. 

Check whether missingness follows a pattern. For example, a survey question might be skipped by a specific group. That pattern can guide the imputation strategy. If missing entirely at random, simple imputation is reasonable. If missingness depends on other variables, use advanced methods. 

Some machine learning models handle missing values natively. For example, certain tree-based models can split on missingness. Always consider whether imputation is necessary. If the model tolerates missing values, you might skip this step. Otherwise, choose a method based on the data. 

## Implementing imputation in scikit-learn 

Scikit-learn provides SimpleImputer, KNNImputer, and IterativeImputer. Each follows the same fit and transform pattern. You import the class, create an instance, fit it on the training data, and transform both train and test data. This keeps your evaluation honest. 

You can combine multiple imputers and models in a scikit-learn Pipeline. A typical pipeline has an imputer followed by a scaler and then a model. The pipeline automates the sequence and prevents data leakage. It also makes cross-validation easier. 

Here is a simple code structure for SimpleImputer. First, import SimpleImputer from sklearn.impute. Then create the imputer with strategy='median'. Fit the imputer on the training DataFrame and transform it. Finally, transform the test data using the fitted imputer. 

## Missing data imputation questions 

### How do you calculate missing values in Python? 

You calculate missing values in Python by using imputation methods. For a mean or median fill, use pandas fillna or SimpleImputer. Python does not calculate a single universal value; you choose the statistic or model. The correct method depends on the data type and missingness pattern. 

### How to handle missing values in dataset Python? 

To handle missing values in a dataset with Python, first identify the columns with missing data. Then decide whether to delete rows, drop columns, or impute values. Python libraries like pandas and scikit-learn provide tools for each option. Imputation is often the best choice to preserve data. 

### What is the difference between SimpleImputer and KNNImputer? 

SimpleImputer fills missing values with a fixed strategy like the mean or median. KNNImputer looks at similar rows and calculates a weighted average from their values. KNNImputer captures local patterns but is slower. SimpleImputer is faster but ignores relationships between rows. 

### When should you not impute missing data? 

You should not impute missing data when the missingness is so high that a column loses meaning. You may also skip imputation if your model handles missing values natively. In some cases, deleting rows with missing values is better than introducing bias through imputation. Always assess the impact first. 

### Does imputation always improve machine learning models? 

Imputation does not always improve machine learning models. The improvement depends on the imputation method and the true missing data mechanism. Poor imputation can distort the data and degrade model performance. It is important to compare models with different imputation strategies.
