Pandas DataFrame squeeze() Method

4/5 - (1 vote)

Preparation

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

  • The Pandas library enables access to/from a DataFrame.
  • The Xarray library works with labeled multi-dimensional arrays and advanced analytics.

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

DataFrame squeeze()

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)
ParameterDescription
axisIf 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)
  • Line [1] creates a DataFrame, assigns the column names, and saves it to df.
  • Line [2] outputs the DataFrame to the terminal.
  • Line [3] slices out the column containing Chopin’s composition details and saves it to col.
  • Line [4] squeezes the column. The output saves to result.
  • Line [5] outputs the result to the terminal.

Output

df

 DebussyChopin
02418
1421

result

018
121
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.