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:
DataFrame.shape
Syntax for the DataFrame.shape attribute in Pandas
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 moduleimport pandas as pd# creating a dataframedf = 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 dataframeprint(df)# obtaining the shape of the DataFrameshape = df.shapeprint(shape)
Explanation
- Line 4: We import the
pandaslibrary. - Line 7: We create a DataFrame and name it
dfusing thepandas.DataFrame()function. - Line 12: We print the DataFrame,
df. - Line 15: We obtain the row labels of the index
dfusing theDataFrame.shapeattribute. 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.