Pandas DataFrame squeeze() method with examples

Spread the love

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

syntax –


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']})

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

<class 'pandas.core.frame.DataFrame'>

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

s = df.squeeze()

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

<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]})

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

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

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()
Name     Lucas
Age         20
Marks       80
Name: 4, dtype: object

Rating: 1 out of 5.

Leave a Reply