How to return the shape of a DataFrame in Pandas

Overview

The shape of a DataFrame is a tuple of array dimensions that tells the number of rows and columns of a given DataFrame.

The DataFrame.shape attribute in Pandas enables us to obtain the shape of a DataFrame. For example, if a DataFrame has a shape of (80, 10) , this implies that the DataFrame is made up of 80 rows and 10 columns of data.

Syntax

The DataFrame.shape takes the syntax below:

Error: Code Block Widget Crashed, Please Contact Support

Parameter

The DataFrame.shape takes no parameter value.

Return value

The DataFrame.shape returns a tuple of array dimensions representing the shape of a given DataFrame.

Example

Let's look at the code below:

# A code to illustrate the DataFrame.shape attribute in Pandas
# importing the pandas module
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'Nme': {0: 'Alek', 1: 'Akim', 2: 'Cynthia'},
'Age': {0: 20, 1: 30, 2: 50},
'Sex': {0: "Male", 1: "Male", 2: "Female"}})
# printing the dataframe
print(df)
# obtaining the shape of the DataFrame
shape = df.shape
print(shape)
Using the DataFrame.shape attribute in Pandas

Explanation

  • Line 4: We import the pandas library.
  • Line 7: We create a DataFrame and name it df using the pandas.DataFrame() function.
  • Line 12: We print the DataFrame, df.
  • Line 15: We obtain the row labels of the index  df using the DataFrame.shape attribute. We assign the result to a variable, shape.
  • Line 16: We print the value of the variable, shape.

Output

In the code above, we can see that the DataFrame has 3 rows and 3 columns.

Free Resources