Examples

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

Slicing might produce a Series with a single value:

In [3]:
even_primes = primes[primes % 3 == 0]
even_primes
Out[3]:
0    3
3    9
dtype: int64
In [4]:
even_primes.squeeze()
Out[4]:
0    3
3    9
dtype: int64

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
1    5
2    7
3    9
dtype: int64
In [6]:
odd_primes.squeeze()
Out[6]:
0    3
1    5
2    7
3    9
dtype: int64

Squeezing is even more effective when used with DataFrames:

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

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

In [8]:
df_p = df[['p']]
df_p
Out[8]:
p
0 2
1 4

Columns can be squeezed down, resulting in a Series:

In [9]:
df_p.squeeze('columns')
Out[9]:
0    2
1    4
Name: p, dtype: int64
In [10]:
df_0p = df.loc[df.index < 1, ['p']]
df_0p
Out[10]:
p
0 2

Squeezing the rows produces a single scalar Series:

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

Squeezing all axes will project directly into a scalar:

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