Convert a singleton column selection to a Series
A pipeline selects one column but retains DataFrame shape.
Pandas · Module
Remove DataFrame axes of length one. Depending on the shape and selected axis, the result is a DataFrame, Series, or scalar.
Call squeeze to remove axes of length one. Selecting a single column can yield a Series, selecting a single row can yield a Series, and reducing both dimensions of a one-cell DataFrame yields a scalar; objects without singleton axes remain unchanged.
DataFrame.squeeze(axis=None)| Name | Type | Description |
|---|---|---|
axis | {0 or 'index', 1 or 'columns', None}, default None | Axis to squeeze: 0 or "index", 1 or "columns", or None; defaults to None. With None, all length-one axes are squeezed. |
DataFrame, Series, or scalar — the projection after squeezing the selected axis or all axes.
import pandas as pd
df = pd.DataFrame([[1], [3]], columns=["a"])
series = df.squeeze("columns")
value = pd.DataFrame([[1]]).squeeze()
print(type(series).__name__)
print(value)A one-column DataFrame becomes a Series when the columns axis is squeezed, while a one-cell DataFrame becomes its scalar value.
A pipeline selects one column but retains DataFrame shape.
A filtered table contains one row and one column.
Code accepts either a Series or DataFrame with a known singleton dimension.
DataFrame.squeeze return?DataFrame.squeeze removes dimensions whose length is one. A one-column or one-row DataFrame becomes a Series, while a one-element object becomes a scalar; otherwise the object is unchanged.
Follow-up: What does axis="columns" do? It targets the columns axis, so a DataFrame with exactly one column can be reduced to a Series without squeezing a singleton row axis.
axis parameter?The signature is DataFrame.squeeze(axis=None). axis accepts 0 or "index", 1 or "columns", or None; None squeezes all length-one axes.
Follow-up: Why might explicit axis selection be preferable? It limits the dimensionality change to the intended axis and avoids accidentally reducing a separate singleton dimension.
The return type is a DataFrame, Series, or scalar, representing the projection after squeezing the selected axis or all axes. Therefore callers should account for shape-dependent output types.
Follow-up: How can code normalize a known single-column selection? Select the column while retaining DataFrame shape, then call squeeze("columns") to obtain a Series.
DataFrame.locDataFrame.__getitem__Series.squeeze