In this article we will discuss different ways to count number of all rows in a Dataframe or rows that satisfy a condition.

Let’s create a Dataframe,

Contents of the dataframe empDfObj  are,

Now let’s discuss different ways to count rows in this dataframe.

Count all rows in a Pandas Dataframe using Dataframe.shape

Dataframe.shape

Each Dataframe object has a member variable shape i.e. a tuple that contains dimensions of a dataframe like,

(Number_of_index, Number_of_columns)

First element of the tuple returned by Dataframe.shape contains the number of items in index in a dataframe i.e. basically the number of rows in the dataframe. Let’s use this to count number of rows in above created dataframe i.e.

Output:

Count all rows in a Pandas Dataframe using Dataframe.index

Dataframe.index

Each Dataframe object has a member variable index that contains a sequence of index or row labels. We can calculate the length of that sequence to find out the number of rows in the dataframe i.e.

Output:

Count rows in a Pandas Dataframe that satisfies a condition using Dataframe.apply()

Using Dataframe.apply() we can apply a function to all the rows of a dataframe to find out if elements of rows satisfies a condition or not.
Based on the result it returns a bool series. By counting the number of True in the returned series we can find out the number of rows in dataframe that satisfies the condition.
Let’s see some examples,
Example 1:

Count the number of rows in a dataframe for which ‘Age’ column contains value more than 30 i.e.

Output:

Example 2:

Count the number of rows in a dataframe which contains 11 in any column i.e.

Output:

Example 3:

Count the number of rows in a dataframe which contains NaN in any column i.e.

Output:

Complete example is as follows

Output

 

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.