Machine Learning with Scikit-learn / The Estimator Contract

Transform and pandas output

Lesson 4 of 37. Open to read. No account needed.

Transformers Learn Too

A transformer is an estimator whose job is to change the data rather than predict a target: scale columns, fill gaps, encode text as numbers. It follows the same contract as a model. fit(X) learns something from the rows it is given and stores it in attributes ending with an underscore; transform(X) applies what was learned to any rows; fit_transform(X) does both in one call on the same rows.

The example in this lesson is StandardScaler. In fit it learns each column's mean and standard deviation and stores them in mean_ and scale_. In transform it subtracts the mean and divides by the scale, so that every column has mean 0 and spread 1 on the rows it was fitted on. Several later models need that: a model that measures distances or applies one penalty to every weight treats a column measured in thousands as more important than one measured in units, unless the columns are put on the same footing first.

Learn From the Training Rows Only

Here is the rule that every preprocessing lesson in this course rests on, and it follows from the contract: anything a transformer learns, it must learn from the training rows only, and then apply unchanged to the test rows and to new rows.

One fit, many transforms. The training rows flow into fit, where StandardScaler learns mean_ and scale_. Those statistics flow into transform for the training rows and, separately, for the test or new rows. fit_transform on the training rows is fit followed by transform. A crossed-out arrow shows fitting the scaler again on the test rows, which would learn different statistics and make the columns incomparable.

Read the diagram from the training rows down. fit happens once, on the left. Both transform arrows reuse the same mean_ and scale_: the scaled training rows have mean 0 and spread 1 exactly, and the scaled test rows have whatever those same statistics give them, which is close to 0 and 1 but not equal. The crossed-out arrow is the mistake: fitting a second scaler on the test rows. It learns different statistics, so a test value and a training value of the same raw size no longer land in the same place, and the model is asked about rows prepared differently from the ones it learned on. It also uses information from the test rows, which are supposed to stand in for rows the model has never seen. That second problem is leakage, and the next module shows how pipelines make it impossible.

DataFrames In, DataFrames Out

Transformers return NumPy arrays by default, and an array has no column names. When the input is a DataFrame, scikit-learn remembers the column names in feature_names_in_, and get_feature_names_out() names the output columns. To get a DataFrame back, ask for it:

  • scaler.set_output(transform="pandas") on one estimator makes its transform and fit_transform return DataFrames.
  • sklearn.set_config(transform_output="pandas") does it for every transformer in the program from that line on.
  • with sklearn.config_context(transform_output="pandas"): does it inside one block.

A pipeline passes the setting to its steps, so the next module uses the same call on a whole pipeline. Named columns matter once you inspect what a model learned: a coefficient table with real column names is readable, and an array of weights is not.

Exercise: Scale the Wine Data

You will fit a scaler on the training rows of three wine columns, transform both splits with pandas output, and compare what the test rows look like with what a scaler fitted on them would have learned.

Starting state: the course environment, active in your terminal.

  1. Create the lesson folder. macOS and Linux:

    mkdir -p ~/sklearn-practice/transform-and-pandas-output
    cd ~/sklearn-practice/transform-and-pandas-output
    

    Windows PowerShell:

    mkdir $HOME\sklearn-practice\transform-and-pandas-output
    cd $HOME\sklearn-practice\transform-and-pandas-output
    
  2. Save this as scale_wine.py:

    """Fit a scaler on the training rows only and apply it to the test rows."""
    from sklearn.datasets import load_wine
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    
    wine = load_wine(as_frame=True)
    X = wine.data[["alcohol", "malic_acid", "proline"]]
    y = wine.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
    print("Rows: train", len(X_train), "| test", len(X_test))
    
    scaler = StandardScaler().set_output(transform="pandas")
    scaled_train = scaler.fit_transform(X_train)
    scaled_test = scaler.transform(X_test)
    
    print("Feature names in:", scaler.feature_names_in_.tolist())
    print("Learned means:", scaler.mean_.round(2).tolist())
    print("Learned scales:", scaler.scale_.round(2).tolist())
    print("Output type:", type(scaled_test).__name__, "| shape:", scaled_test.shape, "| columns:", scaled_test.columns.tolist())
    print("Training column means:", scaled_train.mean().round(3).tolist())
    print("Training column spreads:", scaled_train.std(ddof=0).round(3).tolist())
    print("Test column means:", scaled_test.mean().round(3).tolist())
    print("Test column spreads:", scaled_test.std(ddof=0).round(3).tolist())
    print("First test row, raw:", X_test.iloc[0].tolist())
    print("First test row, scaled:", scaled_test.iloc[0].round(3).tolist())
    
    wrong = StandardScaler().fit(X_test)
    print("A scaler fitted on the test rows learns means:", wrong.mean_.round(2).tolist())
    
  3. Predict, before running: will the test column means be exactly 0? Then run it:

    python scale_wine.py
    

    Output (every value should match):

    Rows: train 133 | test 45
    Feature names in: ['alcohol', 'malic_acid', 'proline']
    Learned means: [13.02, 2.33, 754.2]
    Learned scales: [0.81, 1.14, 323.6]
    Output type: DataFrame | shape: (45, 3) | columns: ['alcohol', 'malic_acid', 'proline']
    Training column means: [0.0, 0.0, -0.0]
    Training column spreads: [1.0, 1.0, 1.0]
    Test column means: [-0.105, 0.03, -0.089]
    Test column spreads: [0.992, 0.89, 0.874]
    First test row, raw: [13.32, 3.24, 650.0]
    First test row, scaled: [0.368, 0.797, -0.322]
    A scaler fitted on the test rows learns means: [12.94, 2.36, 725.31]
    

How the Script Works

load_wine(as_frame=True) returns the 178 wines as a DataFrame in wine.data and the three classes in wine.target; the script keeps three of the thirteen columns so that the output stays short. train_test_split holds out a quarter of the rows; the data lessons explain its options, and here it only matters that 133 rows are training rows and 45 are test rows.

StandardScaler().set_output(transform="pandas") creates the scaler and asks it for DataFrame output in one expression; set_output returns the estimator. fit_transform(X_train) learns the three means and three scales from the 133 training rows and returns those rows scaled. transform(X_test) scales the 45 test rows with the same statistics.

feature_names_in_ holds the column names seen in fit, so the output columns keep those names and the result is a DataFrame of shape (45, 3). The training columns have mean 0 (the -0.0 is a rounding remainder smaller than a thousandth, printed with its sign) and spread 1, by construction. The test columns do not: their means are about -0.1, 0.03 and -0.09, because they were scaled with the training statistics. That is correct, not a defect. The first test row shows the arithmetic: (13.32 - 13.02) / 0.81 is 0.37.

The last line is the mistake made visible. A scaler fitted on the 45 test rows learns means of 12.94, 2.36 and 725.31 instead of 13.02, 2.33 and 754.2. Scaling the test rows with those would put the same raw alcohol of 13.32 at a different scaled value from the one a training row with 13.32 gets, and the model would be comparing rows prepared on two different rulers.

Success: the output type is DataFrame with the three column names, the training means and spreads are 0 and 1, and the test means are not.

If something differs:

What you seeLikely causeNext step
NotFittedError: This StandardScaler instance is not fitted yet.transform called before fit or fit_transformFit on the training rows first
ValueError: The feature names should match those that were passed during fit.The columns of the rows being transformed differ in name or order from fitPass the same columns in the same order
UserWarning: X does not have valid feature names, but StandardScaler was fitted with feature namesAn array was passed to a scaler fitted on a DataFramePass a DataFrame with the fitted columns, or fit on an array too
Output type: ndarrayset_output was not calledAdd .set_output(transform="pandas") or use set_config

Independent task: add a try block that transforms the test rows with their columns in a different order, X_test[["proline", "alcohol", "malic_acid"]], and prints the first line of the error. Predict what happens first: does the scaler reorder the columns for you?

Reset: if an edit goes wrong, save the file again from this lesson and run it again. Any file a script writes is replaced when it runs again, so nothing needs removing first.

Cleanup: when you have finished the independent task, remove the lesson folder. macOS and Linux:

cd ~/sklearn-practice
ls
rm -rf transform-and-pandas-output

Windows PowerShell:

cd $HOME\sklearn-practice
ls
Remove-Item -Recurse transform-and-pandas-output

Check that ls lists transform-and-pandas-output before you remove it, and leave .venv and requirements.txt in place for the next lesson.

Check Your Understanding

  1. The test column means are -0.105, 0.03 and -0.089 rather than 0. Is that a sign something went wrong? What would make them exactly 0, and why would that be the wrong thing to do?
  2. fit_transform(X_test) returns scaled test rows without an error. What is wrong with it?

Answer and Reasoning

Independent task

try:
    scaler.transform(X_test[["proline", "alcohol", "malic_acid"]])
except ValueError as error:
    print("ValueError:", str(error).splitlines()[0])
ValueError: The feature names should match those that were passed during fit.

The scaler does not reorder columns. It compares the names it sees with feature_names_in_ and refuses when the order differs, because its mean_ and scale_ are stored by position: applying the alcohol mean to the proline column would silently produce nonsense, so the check is strict. The error's second line says that the names must be in the same order as in fit.

Understanding check

  1. No. The test rows were scaled with the training statistics, so their means are whatever those statistics give, and a small offset is expected from 45 rows. Fitting the scaler on the test rows would make the means exactly 0, but it would learn from rows that are supposed to be unseen and prepare them on a different ruler from the training rows.
  2. It fits the scaler on the test rows, which is exactly the crossed-out arrow: the test statistics replace the training statistics, and every later transform, including on the training rows, uses them. The absence of an error is what makes this mistake dangerous.

References

32 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy