pandas & polars Output (set_output)
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
By default every scikit-learn transformer returns a NumPy array (or a SciPy sparse matrix), and the column names and the
index of the input DataFrame are lost. That is awkward for inspection, plotting, debugging and for passing a
preprocessed table to another tool. The set_output API makes transformers return a pandas or polars DataFrame with
the original index and meaningful column names. It was introduced for pandas output in scikit-learn 1.2 and extended to
polars output in 1.4; scikit-learn 1.9 added the lightweight library narwhals as a hard dependency to handle pandas,
polars and other data frame libraries uniformly, replacing the data frame interchange protocol that polars deprecated.
This page targets scikit-learn 1.9 (1.9.1 at the time of writing) with pandas 3.1 and NumPy 2.5, plus
polars 2.1 for the polars examples, and was checked in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. The examples were run with those versions and the
output shown is the real output. How these frames flow through preprocessing blocks is described in
ColumnTransformer & Heterogeneous Data and
Pipelines; pandas itself is covered in
the pandas section.
Per-estimator configuration
Every transformer that defines get_feature_names_out has a set_output method. It takes a transform argument:
-
"default"returns the usual NumPy array or sparse matrix. -
"pandas"returns apandas.DataFrame. pandas must be installed. -
"polars"returns apolars.DataFrame. polars must be installed. -
Noneleaves the current configuration of that estimator unchanged, so that it follows the global setting.
set_output returns the estimator itself, so it can be chained with fit. It can also be called after fit to change
how later transform calls return their result, and it needs no refit.
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectPercentile
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
scaler = StandardScaler().set_output(transform="pandas").fit(X_train)
out = scaler.transform(X_test)
print(type(out).__name__)
print(out.head(3).round(3))
print(out.index[:3].tolist(), X_test.index[:3].tolist())
# set_output can be changed after fit
scaler.set_output(transform="default")
print(type(scaler.transform(X_test)).__name__)
# in a pipeline, every transformer step is configured
clf = make_pipeline(StandardScaler(), SelectPercentile(percentile=75), LogisticRegression())
clf.set_output(transform="pandas").fit(X_train, y_train)
selected = clf[:-1].transform(X_test)
print(type(selected).__name__, list(selected.columns))
print(clf[-1].feature_names_in_)
Output:
DataFrame
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
39 -0.894 0.798 -1.271 -1.328
12 -1.244 -0.087 -1.327 -1.459
48 -0.661 1.462 -1.271 -1.328
[39, 12, 48] [39, 12, 48]
ndarray
DataFrame ['sepal length (cm)', 'petal length (cm)', 'petal width (cm)']
['sepal length (cm)' 'petal length (cm)' 'petal width (cm)']
The output keeps the row labels of the input (the index 39, 12, 48 of the test split) and the column names. The
pipeline example shows the chain of consequences: the scaler hands a DataFrame to SelectPercentile, which keeps three
named columns, and the final classifier learns feature_names_in_ from them. A classifier at the end of a pipeline is
not a transformer, so set_output on the pipeline only configures the transformer steps and leaves the last estimator
alone; predict is unaffected.
Global configuration
The same choice can be made for the whole session with sklearn.set_config(transform_output=...), or for a block of
code with the config_context context manager. The accepted values are "default", "pandas" and "polars". An
estimator-level setting always wins over the global one, and set_output(transform=None) hands control back to the
global setting.
import pandas as pd
import sklearn
from sklearn import config_context
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
df = pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [3.0, 1.0, 2.0]}, index=["x", "y", "z"])
print(sklearn.get_config()["transform_output"])
# the global setting, here limited to a block
with config_context(transform_output="pandas"):
print(type(StandardScaler().fit_transform(df)).__name__)
print(type(StandardScaler().fit_transform(df)).__name__)
# an explicit estimator setting wins over the global one, and None defers to it
sklearn.set_config(transform_output="pandas")
print(type(StandardScaler().set_output(transform="default").fit_transform(df)).__name__)
print(type(StandardScaler().set_output(transform=None).fit_transform(df)).__name__)
sklearn.set_config(transform_output="default")
scaler = StandardScaler().set_output(transform="pandas")
print(type(scaler.fit_transform(df)).__name__)
# the names come from get_feature_names_out
poly = PolynomialFeatures(degree=2, include_bias=False).set_output(transform="pandas")
print(list(poly.fit_transform(df).columns))
# NumPy input gets generated names
print(list(StandardScaler().set_output(transform="pandas").fit_transform(df.to_numpy()).columns))
Output:
default DataFrame ndarray ndarray DataFrame DataFrame ['a', 'b', 'a^2', 'a b', 'b^2'] ['x0', 'x1']
The first line is the default configuration. Inside the config_context block the scaler returns a DataFrame and
outside it returns an array again. After set_config(transform_output="pandas"), an estimator explicitly set to
"default" still returns an array, while one set to None follows the global value. The last two lines show where the
names come from: the transformer’s get_feature_names_out, which yields a^2 and a b for polynomial features, or the
generated x0, x1 when the input was a NumPy array without column names.
Global configuration is convenient in a notebook, but it changes the behaviour of every scikit-learn call, including
those made by libraries you import, so in application code prefer the explicit per-estimator form or a
config_context block. set_config can also be called once at the start of a script.
Polars input and output
With scikit-learn 1.9 the same API works with polars. Input and output types are independent: a transformer can read a polars frame and return pandas, read pandas and return polars, or read polars and return a plain array. The polars examples below were run with polars 2.1.0 installed next to the other libraries.
import polars as pl
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.decomposition import PCA
from sklearn import config_context
from sklearn.preprocessing import StandardScaler
print("polars", pl.__version__)
pdf = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0], "b": [10.0, 20.0, 15.0, 5.0], "c": ["x", "y", "x", "y"]})
pldf = pl.from_pandas(pdf)
out = StandardScaler().set_output(transform="polars").fit_transform(pldf.select("a", "b"))
print(type(out))
print(out)
# input and output types are independent
print(type(StandardScaler().set_output(transform="polars").fit_transform(pdf[["a", "b"]])))
print(type(StandardScaler().set_output(transform="pandas").fit_transform(pldf.select("a", "b"))))
default = StandardScaler().fit_transform(pldf.select("a", "b"))
print(type(default).__name__, default.shape)
print(StandardScaler().fit(pldf.select("a", "b")).feature_names_in_)
# a ColumnTransformer selects polars columns by name
ct = make_column_transformer((StandardScaler(), ["a", "b"]), verbose_feature_names_out=False)
print(ct.set_output(transform="polars").fit_transform(pldf))
with config_context(transform_output="polars"):
print(type(PCA(n_components=1).fit_transform(pldf.select("a", "b"))))
Output:
polars 2.1.0 <class 'polars.dataframe.frame.DataFrame'> shape: (4, 2) ┌───────────┬───────────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═══════════╪═══════════╡ │ -1.341641 ┆ -0.447214 │ │ -0.447214 ┆ 1.341641 │ │ 0.447214 ┆ 0.447214 │ │ 1.341641 ┆ -1.341641 │ └───────────┴───────────┘ <class 'polars.dataframe.frame.DataFrame'> <class 'pandas.DataFrame'> ndarray (4, 2) ['a' 'b'] shape: (4, 2) ┌───────────┬───────────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═══════════╪═══════════╡ │ -1.341641 ┆ -0.447214 │ │ -0.447214 ┆ 1.341641 │ │ 0.447214 ┆ 0.447214 │ │ 1.341641 ┆ -1.341641 │ └───────────┴───────────┘ <class 'polars.dataframe.frame.DataFrame'>
Three points need attention. A polars frame has no row index, so polars output carries column names only and there is
no index to preserve. scikit-learn learns feature_names_in_ from polars input just as it does from pandas, which means
the feature-name checks described below apply to polars as well. And polars and pandas remain optional dependencies: the
only hard dependency added in 1.9 is narwhals. The 1.9.1 release notes also record a fix so that polars output no
longer emits a deprecation warning with recent polars versions.
Source: scikit-learn API reference: set_config and the 1.9 release notes.
Custom transformers
A transformer written by a user gets set_output for free when it inherits from TransformerMixin and defines
get_feature_names_out. The mixin wraps transform and fit_transform so that their result is converted to the
requested container, using the index of the input and the names returned by get_feature_names_out. A transformer
without get_feature_names_out does not get the method at all, because scikit-learn cannot name the output columns.
To opt out explicitly, pass auto_wrap_output_keys=None as a class keyword argument.
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import make_column_transformer
from sklearn.decomposition import PCA
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0], "b": [10.0, 20.0, 15.0, 5.0], "c": ["x", "y", "x", "y"]})
class Ratio(TransformerMixin, BaseEstimator):
"""Divide the first column by the second."""
def fit(self, X, y=None):
self.n_features_in_ = X.shape[1]
return self
def transform(self, X):
X = np.asarray(X)
return X[:, [0]] / X[:, [1]]
def get_feature_names_out(self, input_features=None):
return np.array(["ratio"])
class NoNames(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
return self
def transform(self, X):
return np.asarray(X) * 2
print(Ratio().set_output(transform="pandas").fit_transform(df[["a", "b"]]))
print(hasattr(Ratio(), "set_output"), hasattr(NoNames(), "set_output"))
# estimators with a class-name prefix generate names such as pca0, pca1
print(list(PCA(n_components=2).set_output(transform="pandas").fit_transform(df[["a", "b"]]).columns))
# sparse results cannot become a DataFrame
ct = make_column_transformer((OneHotEncoder(), ["c"])).set_output(transform="pandas")
try:
ct.fit_transform(df)
except ValueError as exc:
print("ValueError:", str(exc)[:70])
ct = make_column_transformer((OneHotEncoder(sparse_output=False), ["c"])).set_output(transform="pandas")
print(ct.fit_transform(df))
Output:
ratio 0 0.1 1 0.1 2 0.2 3 0.8 True False ['pca0', 'pca1'] ValueError: Pandas output does not support sparse data. Set sparse_output=False to onehotencoder__c_x onehotencoder__c_y 0 1.0 0.0 1 0.0 1.0 2 1.0 0.0 3 0.0 1.0
The last two statements show the most common failure: pandas (and polars) output cannot hold a sparse matrix. A
one-hot encoder inside a ColumnTransformer that is switched to pandas output must either produce dense data with
sparse_output=False or leave pandas output for that step. The sparse-or-dense decision of ColumnTransformer is
explained in ColumnTransformer & Heterogeneous Data.
Feature names and the warnings they produce
Once a model is fitted on a DataFrame it remembers the column names in feature_names_in_. Keeping names consistent
through the whole workflow is the main benefit of DataFrame output, and the library checks them:
import warnings
import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.DataFrame({"a": [1, 2, 3, 4, 5, 6], "b": [10, 20, 15, 5, 8, 9]})
y = [0, 0, 1, 1, 0, 1]
model = LogisticRegression().fit(df, y)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
model.predict(df.to_numpy())
print([str(w.message) for w in caught])
try:
model.predict(df.rename(columns={"a": "z"}))
except ValueError as exc:
print("ValueError:", str(exc).splitlines()[0])
Output:
['X does not have valid feature names, but LogisticRegression was fitted with feature names'] ValueError: The feature names should match those that were passed during fit.
A model fitted with names that receives an array only warns, because the columns can no longer be verified; one that
receives different names raises an error. Feeding the output of a pandas-configured preprocessor to a model fitted on
raw arrays, or the other way round, is therefore detected. Column labels must either all be strings or all be
non-strings: a mix of strings and integers raises a TypeError, and integer-only labels are accepted but not recorded
(no feature_names_in_ is set), so use string names.
Things to remember
-
Output is converted after the transformer has computed it;
set_outputdoes not make the algorithm work on DataFrames. -
The output of a transformer that changes the data (scaling, imputing, encoding) is numeric. The original column dtypes, such as categories or integers, are not guaranteed to be preserved; check the dtypes of the result when it matters.
-
The accepted values of the
transformargument are"default","pandas","polars"andNone. -
A frame configured for pandas output stays a normal DataFrame: after the preprocessing step you can pass it to plotting, to statistics code or to another model library.
Where older books and tutorials are outdated
Before scikit-learn 1.2 there was no set_output; the standard advice was to rebuild a DataFrame by hand with
pd.DataFrame(Xt, columns=..., index=...) and to call get_feature_names(). That method was replaced by
get_feature_names_out(). Recipes that wrap each transformer in a
custom class returning a DataFrame are no longer needed. Tutorials that predate scikit-learn 1.4 mention only pandas
output; polars output arrived in 1.4. Tutorials written before 1.9 also mention the data frame interchange protocol
(__dataframe__) as the mechanism for non-pandas frames; scikit-learn 1.9 replaced it with narwhals. See
What’s New for the full list.