Q:

How to get the number of rows in DataFrame?

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to count the NaN values in a column in Pandas ... >>
<< How to get a list from Pandas DataFrame column hea...