Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsSimpleImputer fills missing values one feature at a time, using a statistic learned from that feature’s observed values or a fixed replacement. It is a practical baseline for tabular machine learning—but to avoid data leakage, fit it only on training data and keep it inside the same scikit-learn pipeline as the model.
What SimpleImputer does
Many machine-learning estimators cannot work directly with missing values. scikit-learn’s SimpleImputer replaces them separately in each feature; it does not use relationships among multiple features to reconstruct a value. The fitted statistic for one column is applied to every missing value in that column, rather than calculating one statistic for the whole input matrix. See the SimpleImputer API reference.
A missing value might be represented by np.nan, None, pd.NA, or a dataset-specific sentinel such as -1 or "?". Blank strings also need attention: they are not automatically treated as np.nan. Normalize markers that mean “missing” before fitting, without converting valid values—such as a legitimate zero—by mistake:
import numpy as np
df = df.replace("?", np.nan)
df["age"] = df["age"].replace(-1, np.nan)
The default marker is np.nan. You can instead set missing_values to a marker such as -999 or a string. For pandas nullable integer columns, the API recommends using np.nan, since pd.NA may be converted to it.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Run a basic imputation
This example learns the median of each numeric column and uses it to fill missing values in that column:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([
[10.0, 1.0],
[np.nan, 2.0],
[30.0, np.nan],
])
imputer = SimpleImputer(strategy="median")
X_imputed = imputer.fit_transform(X)
print(imputer.statistics_)
print(X_imputed)
fit calculates the per-column statistics; transform applies statistics already learned; fit_transform does both. The learned values are available as statistics_, and n_features_in_ reports the number of input features. In a predictive workflow, call fit_transform on training data only, not the full dataset.
Choose an imputation strategy
In the current API, the built-in choices are mean, median, most_frequent, and constant. A callable custom statistic is also supported in scikit-learn 1.5 and newer. Choose based on the feature’s meaning and validate alternatives on the task rather than assuming one strategy is always best.
| Strategy | Suitable use | Trade-off |
|---|---|---|
mean |
Numeric features with reasonably symmetric distributions and no influential outliers. | Skew and extreme values can pull the average away from a typical observation. |
median |
Numeric features, especially when skew or outliers make the mean less representative. | It is a robust starting point, not a universal winner; imputation can still distort variation and relationships. |
most_frequent |
Categorical features, or discrete numeric features, when filling with an observed value makes sense. | May inflate the dominant category. If several values tie, the smallest value is returned. |
constant |
A dedicated missing category, a domain-specific default, or a replacement required by later processing. | The chosen value may be mistaken for an ordinary observation unless the distinction is preserved. |
| Callable | A custom per-feature statistic, such as a percentile or trimmed mean. | Requires a well-defined rule and validation. |
Mean and median for numeric data
mean and median are numeric-only strategies. Mean is easy to interpret but sensitive to skew and outliers. Median is often a safer baseline for skewed or outlier-prone features, but compare both through validation when the choice could affect model quality.
Most frequent for categorical data
Use the most frequent value when missing entries should take an existing category and there is a meaningful dominant value. Because this can conceal missingness and increase that category’s apparent frequency, consider a dedicated missing category or an indicator when absence itself may carry information.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Constant for a deliberate replacement
Set fill_value when strategy="constant". For example, use a distinct category for strings or a domain-appropriate numeric value:
SimpleImputer(strategy="constant", fill_value="Missing")
SimpleImputer(strategy="constant", fill_value=-999)
If fill_value=None, the documented default is 0 for numerical data and "missing_value" for strings or object data. For string or object columns, fill_value must be a string.
Callable for a custom statistic
A callable receives a dense one-dimensional array of the non-missing values from one feature and must return one scalar. This example trims the lowest and highest values when there are at least three observations:
import numpy as np
from sklearn.impute import SimpleImputer
def trimmed_mean(values):
values = np.sort(values)
if len(values) < 3:
return np.mean(values)
return np.mean(values[1:-1])
imputer = SimpleImputer(strategy=trimmed_mean)
Callable strategies require scikit-learn 1.5 or newer. Check your installed version with sklearn.__version__ before relying on version-specific features.
Prevent leakage: fit on training data only
If the imputer learns its statistics from the test set, information from that set influences preprocessing before evaluation. This is preprocessing leakage, even though the target labels are not used to calculate the medians. Split first, then fit on the training partition and transform the test partition with those learned values:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
imputer = SimpleImputer(strategy="median")
X_train_imputed = imputer.fit_transform(X_train)
X_test_imputed = imputer.transform(X_test)
Avoid calling fit_transform on all of X and splitting the result afterward. For cross-validation, put preprocessing in a pipeline so each training fold learns its own imputation statistics.
Keep preprocessing and the estimator together
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestRegressor
model = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("model", RandomForestRegressor(
n_estimators=300,
random_state=42
)),
])
model.fit(X_train, y_train)
predictions = model.predict(X_test)
The pipeline applies the learned imputation as part of fitting and prediction. It also makes cross-validation and parameter searches use preprocessing within each training split. Nested parameters use the step__parameter form:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
from sklearn.model_selection import GridSearchCV
param_grid = {
"imputer__strategy": ["mean", "median"],
"model__max_depth": [None, 10, 20],
}
search = GridSearchCV(
model,
param_grid=param_grid,
cv=5,
scoring="neg_root_mean_squared_error",
)
search.fit(X_train, y_train)
The scoring metric and search space should suit the problem; these values are examples, not general recommendations. See scikit-learn’s pipeline example.
Preprocess numeric and categorical columns separately
Mixed-type tables need different strategies for different columns. A ColumnTransformer can route numeric and categorical features through their own pipelines. Impute categorical values before one-hot encoding:
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
numeric_features = ["age", "income"]
categorical_features = ["city", "plan"]
numeric_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
])
categorical_pipeline = Pipeline([
("imputer", SimpleImputer(
strategy="constant",
fill_value="Missing"
)),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
preprocessor = ColumnTransformer([
("numeric", numeric_pipeline, numeric_features),
("categorical", categorical_pipeline, categorical_features),
])
model = Pipeline([
("preprocessor", preprocessor),
("classifier", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
Here, handle_unknown="ignore" allows the encoder to process categories not seen during fitting; it does not impute missing values. Make sure the named columns exist in the data passed to the pipeline.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Preserve missingness when it may be useful
An imputed value alone looks like an observed value to a downstream estimator. If missingness may contain predictive information, add_indicator=True appends binary indicators for features that had missing values during fitting:
imputer = SimpleImputer(
strategy="median",
add_indicator=True
)
Indicators are created only for features that contained missing values during fit. If a previously complete feature first becomes missing at prediction time, the imputer can fill it, but it will not add a new indicator column for that feature. Indicators add inputs and do not necessarily improve performance, so compare them through cross-validation.
Parameters and output behavior to check
missing_values and fill_value
missing_values identifies the marker to replace; for instance, set it to -999 if that sentinel means missing in the data. Alternatively, normalize sentinels before the pipeline. fill_value matters only for the constant strategy. Treat marker definitions as part of the data contract: a sentinel left unrecognized is processed as an ordinary observation.
keep_empty_features
If a feature is entirely missing during fitting, there is no observed statistic to calculate. With the default keep_empty_features=False, an all-missing feature is generally dropped at transform time for non-constant strategies. Set keep_empty_features=True to retain it; it is filled with 0, except with the constant strategy, which uses fill_value. This can help preserve a fixed schema, but a retained column with no observed training values may have little useful information. The parameter was added in scikit-learn 1.2.
Output containers and feature names
Transformers commonly return arrays by default. In supported versions, configure output as pandas or Polars with set_output:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
imputer = SimpleImputer(strategy="median").set_output(
transform="pandas"
)
X_imputed = imputer.fit_transform(X_train)
The API documents "default", "pandas", and "polars" modes; Polars output was added in scikit-learn 1.4. Check sklearn.__version__ in the environment where the code runs.
copy and inverse_transform
copy=False is only an optimization hint, not a guarantee of in-place mutation. A copy is still made for documented cases such as non-floating-point input, CSR sparse input, or add_indicator=True.
inverse_transform is not a general way to recover every original missing value. It requires binary indicators created by add_indicator=True, and there are no such indicators for features complete during fitting. See the scikit-learn 1.2 API reference for this behavior.
Common failure modes and safeguards
- Mean or median on strings: these strategies are numeric-only. Use a categorical strategy or separate the columns with a
ColumnTransformer. - Wrong missing marker:
-1,"?", and blank strings are not automatically equivalent tonp.nan. Normalize or specify the marker before fitting. - All-missing columns disappearing: inspect these features, then deliberately remove them or retain them with
keep_empty_features=Trueif the schema requires it. - Column order changing: array-based input is positional. Applying an imputer to a differently ordered array can silently give values to the wrong features. Prefer DataFrames and named-column transformers where practical.
- Missing targets: do not automatically use feature imputation to fill a missing supervised-learning target. Excluding those rows or using a domain-specific target process is a separate decision.
- Derived features: decide whether to impute source features before calculating a derived feature, calculate it only when valid, or impute both separately. The order can change the variable’s meaning.
- Changed deployment data: the training statistic may become unsuitable if the deployment population changes. Track missingness and imputed-value rates, including new missingness in features that were complete during fitting.
When another approach may fit better
Simple imputation is not value reconstruction: it replaces an unknown with a rule-based value and does not express the uncertainty in that estimate. More complex methods are not automatically more accurate; scikit-learn notes that simple imputation can match or outperform complex methods with a powerful learner. Compare the complete modeling workflow on suitable validation data.
Recommended Free Tools
| Approach | When it may fit | Considerations |
|---|---|---|
SimpleImputer |
A transparent, fast baseline using a per-feature statistic or fixed value. | Does not model relationships among features. |
KNNImputer |
Nearby samples may provide useful information for estimating a missing value. | Uses a distance measure and can cost more; feature scaling, irrelevant variables, and sparse observations can affect results. See the KNNImputer implementation. |
IterativeImputer |
Other features may help estimate each feature through repeated modeling rounds. | Adds modeling choices, computational cost, and potential instability. The IterativeImputer documentation describes it as multivariate and notes that it starts with a SimpleImputer. |
| Drop rows or columns | Missingness is rare, a column is mostly empty and low-value, or observed measurements are essential. | Can discard useful data or bias a dataset when missingness is concentrated in a subgroup. |
| Domain-specific rule | Time ordering, groups, or domain meaning makes a generic statistic inappropriate—for example, carrying the last observation forward in a time series. | Document the rule and validate it; distinguish “not applicable” from “unknown” where the domain requires it. |
pandas.DataFrame.fillna |
Exploratory analysis or one-off cleaning outside a fitted estimator workflow. | For predictive preprocessing, a manually applied rule can be harder to reproduce correctly across training folds and serving. |
Validate and monitor the complete workflow
Compare candidate strategies by evaluating the pipeline, not by choosing whichever produces the neatest transformed table. Keep preprocessing within cross-validation so each fold learns only from its training portion. For deployed models, monitor missingness rates, the share of values imputed, and imputed-value frequencies over time; SimpleImputer does not detect changes in the meaning or distribution of missingness by itself.
Quick Recap
- Normalize documented missing markers without changing legitimate observations.
- Use strategies appropriate to each feature’s data type.
- Fit imputers within the training workflow, ideally in a pipeline.
- Inspect all-missing columns and decide whether to retain them.
- Validate indicators and alternative imputers rather than assuming they help.
- Keep the same fitted preprocessing workflow for evaluation and prediction.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

