Skip to main content

How to Count the Rows of a pandas DataFrame with len

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

How many rows does a table have? In pandas, len(df) answers in one call. df.shape gives rows and columns together, and len on a filtered table counts the rows that meet a condition. This guide does all three with pandas 3.1.2 on Python 3.15.2.

Syntax​

Syntax
<rows> = len(<table>)
<rows>, <columns> = <table>.shape
PartWhat it means
len(<table>)The number of rows
<table>.shapeA pair: the number of rows and the number of columns

The DataFrame.shape reference compares the two: "Unlike the len() method, which only returns the number of rows, shape provides both row and column counts".

The Example​

A table holds three bike rides, each with a rider and the minutes ridden. The script counts the rides, shows the table's shape and counts the rides longer than 10 minutes.

Prerequisites​

  • pandas in your project, for example with uv add pandas. This guide uses pandas 3.1.2 on Python 3.15.2.

Step 1: Write the Script​

count_rows.py
import pandas as pd

rides = pd.DataFrame({"rider": ["Ada", "Grace", "Alan"], "minutes": [12, 30, 7]})

print(len(rides))
print(rides.shape)
print(len(rides[rides["minutes"] > 10]))

The count_rows.py script in a macOS-style code window: a rides DataFrame with rider and minutes, then prints of len(rides), rides.shape and the length of the rides over 10 minutes.

Step 2: Run It​

Terminal
uv run python count_rows.py
Output
3
(3, 2)
2

The terminal after uv run python count_rows.py: 3, then (3, 2), then 2.

len(rides) counted 3 rows. shape returned (3, 2): 3 rows and 2 columns. Two rides were longer than 10 minutes, Ada's and Grace's. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Reading shape as a single numberIt's a pair, (3, 2)Use rides.shape[0] for rows, or len(rides)
Expecting len to count columnsIt counts rowsUse len(rides.columns), which printed 2

Troubleshooting​

SymptomLikely causeFix
len returns 0 after a filterNo row meets the conditionPrint the condition alone to see its True and False values

FAQ​

How do I count the columns?​

With len(rides.columns), which printed 2, or with rides.shape[1].

Conclusion​

len(rides) counted 3 rows, rides.shape gave (3, 2), and len on a filtered table counted the 2 long rides. Use len for rows and shape when you need both numbers.

Additional Resources​