Missing feature values can stop model training before scikit-learn learns anything from the data. The Input X contains NaN error means the estimator rejected missing values in its feature matrix, which a SimpleImputer pipeline can replace before fitting.

Some scikit-learn estimators accept NaN natively, but LogisticRegression rejects it. For numeric columns with observed training values, median imputation fills each gap without dropping affected rows or treating unknown values as zeros.

Training and held-out rows need the same preprocessing, but only training rows may determine the replacement values. A fitted pipeline keeps the imputer and estimator together so predictions reuse the training statistics instead of learning from the held-out data.

NumPy and scikit-learn must already be installed in the active Python environment. All Python blocks use the same notebook or interactive session.

Steps to fix the Input X contains NaN error in scikit-learn:

  1. Define numeric training data alongside held-out rows containing NaN.
    import numpy as np
    from sklearn.linear_model import LogisticRegression
     
    X_train = np.array([
        [1.0, 10.0],
        [2.0, np.nan],
        [np.nan, 30.0],
        [4.0, 50.0],
    ])
    y_train = np.array([0, 0, 1, 1])
    X_test = np.array([[np.nan, 40.0], [6.0, np.nan]])

    In an existing project, these names can refer to the arrays from the train/test split. Each row is a sample, each column is a numeric feature, and the target labels remain aligned with the training rows.

  2. Reproduce the failing fit without preprocessing.
    LogisticRegression().fit(X_train, y_train)
    ##### snipped #####
    ValueError: Input X contains NaN.
    ##### snipped #####

    This exception identifies missing feature values as the failure. Estimators with native NaN support do not necessarily require this repair.

  3. Locate the NaN values in the training features.
    print(np.argwhere(np.isnan(X_train)))
    [[1 1]
     [2 0]]

    Each pair is a zero-based row and column index. Both columns still have observed values from which a median can be calculated. An entirely missing training column has no median to learn and needs a separate feature-specific decision.

  4. Place a median imputer before LogisticRegression in a pipeline.
    from sklearn.impute import SimpleImputer
    from sklearn.pipeline import Pipeline
     
    model = Pipeline([
        ("imputer", SimpleImputer(strategy="median")),
        ("estimator", LogisticRegression()),
    ])

    The imputer replaces NaN in each numeric feature with that column's fitted median before the estimator receives the data.

  5. Fit the pipeline using only the training rows and labels.
    model.fit(X_train, y_train)

    Fitting the imputer on the full dataset leaks held-out information into training. A separate fit or fit_transform call on the test rows would also replace the learned statistics.

  6. Compare the fitted replacement values with the training-column medians.
    print(model.named_steps["imputer"].statistics_)
    print(np.nanmedian(X_train, axis=0))
    [ 2. 30.]
    [ 2. 30.]

    The matching arrays show the values learned from the nonmissing training entries. Neither held-out row was passed to fit.

  7. Predict labels for the held-out rows through the fitted pipeline.
    predictions = model.predict(X_test)
    print(predictions)
    [1 1]

    Both rows contain NaN, yet each receives a class label without the original exception. Prediction applies the existing imputer before calling LogisticRegression; these two labels demonstrate execution, not model accuracy.

Share this guide