Home »
Python »
Python Programs
How to get the number of rows in DataFrame?
In this tutorial, we will learn how to get the number of rows in Pandas DataFrame?
By Pranit Sharma Last updated : April 12, 2023
Overview
Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. To get the total number of rows, we have DataFrame.shape[0] method.
Get the number of rows of a Pandas DataFrame
To get the number of rows of a Pandas DataFrame, we use DataFrame.shape[0] method, it usually works without an index and it is used to find the total number of rows and columns in a DataFrame, but to find the number of rows specifically, 0 is given as an index. Also, to find the number of columns, 1 is given as an index.
Syntax
# Syntax for both rows and columns
df.shape()
# Syntax for rows
df.shape[0]
Let us understand that how to get the number of rows in a DataFrame with the help of an example?
Python code to get the number of rows in DataFrame
# Importing pandas package
import pandas as pd
# Creating a dictionary of student marks
d = {
"Peter":[65,70,70,75],
"Harry":[45,56,66,66],
"Tom":[67,87,65,53],
"John":[56,78,65,64]
}
# Now, we will create DataFrame and
# we will assign index name as subject names
df = pd.DataFrame(d,index=["Maths","Physics","Chemistry","English"])
# Printing the DataFrame
print(df,"\n")
# Using df.shape[0] method to
# get the number of rows directly
print("Total number of rows are:",df.shape[0])
Output
Peter Harry Tom John
Maths 65 45 67 56
Physics 70 56 87 78
Chemistry 70 66 65 65
English 75 66 53 64
Total number of rows are: 4
Explanation
Here, we have created a DataFrame with four rows having index names Maths, Physics, Chemistry, and English respectively. df.shape[0] method will return the count of the number of rows hence the output is 4.
Python Pandas Programs »