Pandas DataFrame squeeze() method with examples

Spread the love

The squeeze method in pandas converts a pandas DataFrame to a series.

syntax –

DataFrame.squeeze(axis=None)

axis – A specific axis to squeeze. By default, all length-1 axes are squeezed.

Examples –

1 . Convert a Single Column DataFrame to a Series –

Let’s create a DataFrame which has only a single column.

df = pd.DataFrame({'Name':['Max','Will','Eleven','Mike','Lucas']})
df

If you check the type of this object, you will see that it’s a dataframe.

print(type(df))
#output
<class 'pandas.core.frame.DataFrame'>

Now, Let’s convert this dataframe to a series using the squeeze method in pandas.

s = df.squeeze()
s

Now, if we check the type of s, you will see that it is a series.

print(type(s))
#output
<class 'pandas.core.series.Series'>

2 . Convert a Multi Column DataFrame to a series –

Let’s create a DataFrame that has more than one columns.

df = pd.DataFrame({'Name':['Max','Will','Eleven','Mike','Lucas'],
                  'Age':[20, 17, 20, 22, 20],
                  'Marks':[80, 70, 95, 85, 80]})
df

Now, Let’s say that you want to squeeze the Marks column.

s = df['Marks'].squeeze()
s

3. Convert a Row to a Series –

Now, Let’s say that you want to convert a row to a series. Let’s say you want to convert the Lucas data to a series.

s = df.iloc[4].squeeze()
s
Name     Lucas
Age         20
Marks       80
Name: 4, dtype: object

Rating: 1 out of 5.

Leave a Reply