Count no of rows in DataFrame using Pandas in Python

In this tutorial, we are going to learn how to count the no of rows in a DataFrame using pandas in Python. DataFrame is a two-dimensional tabular data structure with labeled axes (rows and columns) generally used to store and manipulate data.

Now, we have to learn how to count the no of rows in the DataFrame. So let’s start.

Count no of rows in a DataFrame

First of all, we have to create a DataFrame using a list or dictionary or series. Let’s create using a dictionary in the following method after importing the module ‘pandas‘.

import pandas as pd
my_dict={'Name':['abc','def','ghi','jkl'],'Roll_no':[21,22,23,24],'Dept':['CS','ME','EE','IT']}
student=['stud1','stud2','stud3','stud4']
df=pd.DataFrame(my_dict,index=student)
print(df)

We can count the no of rows in two different ways.

Count rows using len()

Approach 1:

  • Use ‘.axes[0]‘ to get the list of row indexes. ( N.B- If you use ‘.axes[1]‘, it will give a list of column names)
  • Use ‘len()‘ function to get the length of the above-mentioned list i.e number of rows.

See the below code.

import pandas as pd
my_dict={'Name':['abc','def','ghi','jkl'],'Roll_no':[21,22,23,24],'Dept':['CS','ME','EE','IT']}
student=['stud1','stud2','stud3','stud4']
df=pd.DataFrame(my_dict,index=student)
print(len(df.axes[0]))

Output:

4

Counting rows in a DataFrame usingĀ  .count()

In this approach, we will get column-wise no of not ‘None’ rows.

  • Use ‘.count()‘ function. You can use ‘axis=0’ as parameter. (N.B- If you use ‘axis=1’ as parameter it will give row-wise no of not ‘None’ columns)

See the following code for getting better clarification.

import pandas as pd 
my_dict={'Name':['abc','def',None,'jkl'],'Roll_no':[21,22,23,24],'Dept':['CS','ME','EE','IT']} 
student=['stud1','stud2','stud3','stud4'] 
df=pd.DataFrame(my_dict,index=student)
print(df.count(axis=0))

Output:

Name 3 

Roll_no 4 

Dept 4 

dtype: int64

So, these are the two ways you can count the no of rows in a DataFrame using Python.

You may also read-

Leave a Reply

Your email address will not be published. Required fields are marked *