Pandas DataFrame squeeze() Method – Be on the Right Side of Change (original) (raw)


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install xarray

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd import xarray


The squeeze() method compresses a one-dimensional DataFrame/Series axis into a Series.

💡 Note: Squeezing objects containing more than one element per axis does not change the original DataFrame/Series. This method is most effective when used with a DataFrame.

The syntax for this method is as follows:

DataFrame.squeeze(axis=None)

Parameter Description
axis If zero (0) or index is selected, apply to each column. Default is 0 (column). If zero (1) or columns, apply to each row.

For this example, we have two (2) classical composers. Each composer contains a list with their total number of Preludes and Nocturnes. The DataFrame squeezes to display the details for Chopin.

Code – Example 1

df = pd.DataFrame([[24, 18], [4, 21]], columns=['Debussy', 'Chopin']) print(df)

col = df[['Chopin']] result = col.squeeze('columns') print(result)

Output

df

| | Debussy | Chopin | | | --------- | ------ | -- | | 0 | 24 | 18 | | 1 | 4 | 21 |

result

0 18
1 21
Name: Chopin, dtype: int64

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.