Pandas DataFrame | squeeze method
Start your free 7-days trial now!
Pandas DataFrame.squeeze(~)
method reduces a DataFrame with a single row or column to a Series.
Parameters
1. axis
link | int
or string
| optional
Whether to squeeze the rows or the columns:
Axis | Description |
---|---|
| Squeeze rows. |
| Squeeze columns. |
By default, axis=None
, which means that both rows and columns are considered to see whether any reduction is possible.
Return Value
A Series
if reduction is possible. Otherwise, the source DataFrame
is returned.
Examples
Squeezing a single-column DataFrame
Consider the following DataFrame:
df
A0 31 4
Since our DataFrame only contains a single column, we can reduce it to a Series
like so:
df.squeeze()
A 3B 4Name: 0, dtype: int64
Squeezing a single-row DataFrame
Consider the following DataFrame:
df
A B0 3 4
Since our DataFrame only contains a single row, we can reduce it to a Series
like so:
df.squeeze()
A 3B 4Name: 0, dtype: int64
Specifying the axis parameter
By default, both rows and columns are checked to see whether any reduction is possible. We could restrict this check to either just the row or the column by specifying the axis
parameter.
For instance, consider the following DataFrame:
df
A B0 3 4
If we try to squeeze using the columns, we just get the source DataFrame df
back:
df.squeeze("columns")
A B0 3 4