Question
How can I get the number of rows in a pandas DataFrame named df?
Short Answer
By the end of this page, you will understand several ways to count rows in a pandas DataFrame, when to use each one, and how row counting fits into everyday Python data analysis.
Concept
In pandas, a DataFrame is a 2-dimensional table with rows and columns. Getting the row count means finding out how many records the table contains.
This is one of the most common operations in data analysis because row counts help you:
- inspect dataset size
- validate that data loaded correctly
- compare before/after filtering
- check whether a result is empty
- build summaries and logs
The most common way to get the number of rows is:
df.shape[0]
Why this works:
df.shapereturns a tuple:(number_of_rows, number_of_columns)- index
0gives the first value, which is the row count
You can also use:
len(df)
This also returns the number of rows for a DataFrame.
Both are valid. In practice:
- use
df.shape[0]when you want to be explicit about rows - use
len(df)when you want a short and readable count
This matters in real programming because many data workflows depend on row counts for checks, reporting, filtering, batching, and debugging.
Mental Model
Think of a DataFrame like a spreadsheet.
- Rows are the horizontal entries, like individual records
- Columns are the vertical fields, like name, age, or price
If df.shape is like looking at the spreadsheet size label, then:
- the first number tells you how many rows it has
- the second number tells you how many columns it has
For example, if pandas says:
(5, 3)
that means:
- 5 rows
- 3 columns
So getting the row count is just taking the first number from that size label.
Syntax and Examples
The most common syntax is:
df.shape[0]
Another common option is:
len(df)
Example DataFrame
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cara"],
"age": [22, 31, 27]
})
Get row count with shape
rows = df.shape[0]
print(rows)
Output:
3
Explanation:
df.shapereturns(3, 2)because there are 3 rows and 2 columns[0]selects the first value, which is3
Step by Step Execution
Consider this example:
import pandas as pd
df = pd.DataFrame({
"city": ["Paris", "Tokyo", "Lima", "Cairo"],
"population": [2.1, 13.9, 9.7, 10.0]
})
count = df.shape[0]
print(count)
Step by step:
-
import pandas as pd- Imports the pandas library.
-
df = pd.DataFrame(...)- Creates a DataFrame with 4 records.
- It has 2 columns:
cityandpopulation.
-
df.shape- Returns the size of the DataFrame as a tuple.
- In this case it is:
(4, 2) -
df.shape[0]
Real World Use Cases
Row counts appear in many practical tasks.
1. Checking whether data loaded correctly
df = pd.read_csv("users.csv")
print(df.shape[0])
You can quickly confirm how many records were imported.
2. Counting filtered results
high_value = df[df["price"] > 1000]
print(len(high_value))
Useful for reporting or validation.
3. Detecting empty results
if df.shape[0] == 0:
print("No data found")
This helps avoid errors later in the script.
4. Comparing data before and after cleaning
before = len(df)
df = df.dropna()
after = len(df)
print("Removed rows:", before - after)
Useful in ETL and cleaning pipelines.
5. Logging API or batch processing results
()
Real Codebase Usage
In real projects, developers use row counts as part of larger patterns.
Validation before processing
if df.empty:
raise ValueError("Input DataFrame is empty")
Although this uses df.empty, it is closely related to row counting because an empty DataFrame has 0 rows.
Guard clauses
if len(df) == 0:
return
This stops a function early when there is nothing to process.
Before/after transformation checks
before = df.shape[0]
df = df.drop_duplicates()
after = df.shape[0]
print(f"Removed {before - after} duplicate rows")
Reporting and metrics
summary = {
"total_rows": len(df),
"valid_rows": len(df[df["status"] == "valid"])
}
Filtering pipelines
Common Mistakes
1. Confusing rows and columns
Broken idea:
df.shape[1]
This returns the number of columns, not rows.
Use this instead:
df.shape[0]
2. Forgetting that shape returns a tuple
Broken code:
print(df.shape)
This prints both rows and columns, for example:
(10, 4)
If you only need rows, select the first value:
print(df.shape[0])
3. Using count() to count rows
Broken assumption:
df.count()
count() does not return the number of rows directly. It returns non-missing counts per column.
Comparisons
| Approach | Returns | Best use | Notes |
|---|---|---|---|
df.shape[0] | Number of rows | Explicit row count | Very common and clear |
len(df) | Number of rows | Short, readable code | Also very common |
df.shape[1] | Number of columns | Column count | Not for rows |
df.shape | (rows, columns) tuple | Need full dimensions | Must index into it |
df.count() | Non-null values per column |
Cheat Sheet
Row count
df.shape[0]
len(df)
Column count
df.shape[1]
Rows and columns together
df.shape
Example output:
(100, 5)
Check for empty DataFrame
df.empty
After filtering
filtered = df[df["score"] > 50]
filtered.shape[0]
Avoid this for row count
df.count()
It counts non-null values per column, not total rows.
Quick rule
- use
df.shape[0]for explicit row count - use
len(df)for a short row count
FAQ
How do I get the number of rows in a pandas DataFrame?
Use either:
df.shape[0]
or:
len(df)
Both return the row count.
Is len(df) the same as df.shape[0]?
Yes, for a pandas DataFrame they both return the number of rows.
How do I get the number of columns instead?
Use:
df.shape[1]
How do I check if a DataFrame has no rows?
Use:
df.empty
or compare the row count to zero:
len(df) == 0
Why does df.count() give a different result?
Because df.count() counts non-missing values in each column, not the total number of rows.
Does filtering change the row count?
Mini Project
Description
Build a small data-checking script that loads a pandas DataFrame, reports how many rows it has, filters the data, and compares the counts before and after filtering. This demonstrates how row counts are used in real data-cleaning workflows.
Goal
Create a script that counts total rows, counts filtered rows, and reports whether the result is empty.
Requirements
- Create a pandas DataFrame with at least 5 rows.
- Print the total number of rows.
- Filter the DataFrame using one condition.
- Print the number of rows after filtering.
- Print a message if the filtered DataFrame is empty.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.