Pandas - Count Rows in DataFrame


Pandas DataFrame - Count Rows

To count number of rows in a DataFrame, you can use DataFrame.shape property or DataFrame.count() method.

DataFrame.shape returns a tuple containing number of rows as first element and number of columns as second element. By indexing the first element, we can get the number of rows in the DataFrame

DataFrame.count(), with default parameter values, returns number of values along each column. And in a DataFrame, each column contains same number of values equal to number of rows. By indexing the first element, we can get the number of rows in the DataFrame

Examples

1. Count rows in DataFrame using shape property

In this example, we shall use DataFrame.shape property to get the number of rows in a DataFrame.

Python Program

import pandas as pd

#initialize dataframe
df = pd.DataFrame({'a': [1, 4, 7, 2], 'b': [2, 0, 8, 7]})

#number of rows in dataframe
num_rows = df.shape[0]

print('Number of Rows in DataFrame :',num_rows)

Output

Number of Rows in DataFrame : 4

2. Count rows in DataFrame using count() method

In this example, we shall use DataFrame.count() method, to count the number of rows in a DataFrame.

Python Program

import pandas as pd

#initialize dataframe
df = pd.DataFrame({'a': [1, 4, 7, 2], 'b': [2, 0, 8, 7]})

#number of rows in dataframe
num_rows = df.count()[0]

print('Number of Rows in DataFrame :',num_rows)

Output

Number of Rows in DataFrame : 4

Summary

In this tutorial of Python Examples, we learned how to count the number of rows in a given DataFrame, in different ways, with the help of well detailed example programs.