How to Count the Rows of a pandas DataFrame with len
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
<rows> = len(<table>)
<rows>, <columns> = <table>.shape
| Part | What it means |
|---|---|
len(<table>) | The number of rows |
<table>.shape | A 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
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]))

Step 2: Run It
uv run python count_rows.py
3
(3, 2)
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
| Mistake | What happens | Do this instead |
|---|---|---|
Reading shape as a single number | It's a pair, (3, 2) | Use rides.shape[0] for rows, or len(rides) |
Expecting len to count columns | It counts rows | Use len(rides.columns), which printed 2 |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
len returns 0 after a filter | No row meets the condition | Print 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
- DataFrame.shape — rows and columns together.
- len() — Python's built-in.
