Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
primes = pd.Series([3, 4, 5, 7])

Slicing might produce a Series with a single value:

In [3]:
even_primes = primes[primes % 2 == 0]
even_primes
Out[3]:
1    4
dtype: int64

In [4]:
even_primes.squeeze()
Out[4]:
4

Squeezing objects with more than one value in every axis does nothing:

In [5]:
odd_primes = primes[primes % 2 == 1]
odd_primes
Out[5]:
0    3
2    5
3    7
dtype: int64
In [6]:
odd_primes.squeeze()
Out[6]:
0    3
2    5
3    7
dtype: int64

Squeezing is even more effective when used with DataFrames.

In [7]:
df = pd.DataFrame([[2, 3], [4, 5]], columns=['x', 'y'])
df
Out[7]:
x y
0 2 3
1 4 5

Slicing a single column will produce a DataFrame with the columns having only one value:

In [8]:
df_a = df[['x']]
df_a
Out[8]:
x
0 2
1 4

So the columns can be squeezed down, resulting in a Series:

In [9]:
df_a.squeeze('columns')
Out[9]:
0    2
1    4
Name: x, dtype: int64

Slicing a single row from a single column will produce a single scalar DataFrame:

In [10]:
df_0a = df.loc[df.index < 1, ['x']]
df_0a
Out[10]:
x
0 2

Squeezing the rows produces a single scalar Series:

In [11]:
df_0a.squeeze('rows')
Out[11]:
x    2
Name: 0, dtype: int64

Squeezing all axes will project directly into a scalar:

In [12]:
df_0a.squeeze()
Out[12]:
2