Home »
Python »
Python Programs
How to get the number of rows in DataFrame?
Given a DataFrame, we need to find the total number of rows in this DataFrame.
Submitted by Pranit Sharma, on April 10, 2022
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.
pandas.DataFrame.shape[0] Method
This method 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]
To work with Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Let us understand that how to get the number of rows in a DataFrame with the help of an example?
# 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 »
ADVERTISEMENT
ADVERTISEMENT