Home » How to Count Number of Rows in Pandas DataFrame

How to Count Number of Rows in Pandas DataFrame

by Tutor Aspire

There are three methods you can use to quickly count the number of rows in a pandas DataFrame:

#count number of rows in index column of data frame
len(df.index)

#find length of data frame
len(df)

#find number of rows in data frame
df.shape[0]

Each method will return the exact same answer.

For small datasets, the difference in speed between these three methods is negligible.

For extremely large datasets, it’s recommended to use len(df.index) since this has been shown to be the fastest method.

The following example shows how to use each of these methods in practice.

Example: Count Number of Rows in Pandas DataFrame

The following code shows how to use the three methods mentioned earlier to count the number of rows in a pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'y': [8, 12, 15, 14, 19, 23, 25, 29, 31, 30, 31, 31],
                   'x1': [5, 7, 7, 9, 12, 9, 9, 4, 5, 4, 7, 7],
                   'x2': [11, 8, 10, 6, 6, 5, 9, 12, 8, 8, 9, 9],
                   'x3': [2, 2, 3, 2, 5, 5, 7, 9, 11, 7, 7, 8]})

#view DataFrame
df

	y	x1	x2	x3
0	8	5	11	2
1	12	7	8	2
2	15	7	10	3
3	14	9	6	2
4	19	12	6	5
5	23	9	5	5
6	25	9	9	7
7	29	4	12	9
8	31	5	8	11
9	30	4	8	7
10	31	7	9	7
11	31	7	9	8

#count number of rows in index column of data frame
len(df.index)

12

#find length of data frame
len(df)

12

#find number of rows in data frame
df.shape[0]

12

Notice that each method returns the exact same result. The DataFrame has 12 rows.

Additional Resources

How to Count Observations by Group in Pandas
How to Perform a COUNTIF Function in Pandas
How to Count Missing Values in a Pandas DataFrame

You may also like