Question

How to Get the Row Count of a Pandas DataFrame in Python

pythonpandasdataframe

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.shape returns a tuple: (number_of_rows, number_of_columns)
  • index 0 gives 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.

Take Quiz

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.shape returns (3, 2) because there are 3 rows and 2 columns
  • [0] selects the first value, which is 3

Get row count with len()

rows = len(df)
print(rows)

Output:

3

Explanation:

  • len(df) returns the number of rows in the DataFrame

Get both rows and columns

rows, cols = df.shape
print("Rows:", rows)
print("Columns:", cols)

Output:

Rows: 3
Columns: 2

This is useful when you want the full size of the DataFrame.

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:

  1. import pandas as pd

    • Imports the pandas library.
  2. df = pd.DataFrame(...)

    • Creates a DataFrame with 4 records.
    • It has 2 columns: city and population.
  3. df.shape

    • Returns the size of the DataFrame as a tuple.
    • In this case it is:
    (4, 2)
    
  4. df.shape[0]

    • Gets the first item from the tuple.
    • That first item is the number of rows: 4.
  5. count = df.shape[0]

    • Stores the row count in the variable count.
  6. print(count)

    • Prints:
    4
    

After filtering example

adults = df[df["population"] > 10]
print(adults.shape[0])

This counts only the rows that match the condition, which is a very common pattern in data analysis.

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

print(f"Processing {len(df)} records")

Helps track work during automation jobs.

Take Quiz

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

active_users = df[df["active"] == True]
print("Active users:", active_users.shape[0])

Common pattern:

  • filter rows
  • count remaining rows
  • use that count for validation, logs, or dashboards

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.

Example:

print(df.count())

This may produce something like:

name    3
age     2
dtype: int64

Use len(df) or df.shape[0] for total rows.

4. Ignoring empty DataFrames

If a DataFrame has no rows, row count is 0.

if df.shape[0] == 0:
    print("Empty DataFrame")

5. Overcomplicating the solution

Some beginners write unnecessary code:

rows = 0
for _ in df.index:
    rows += 1

This works, but pandas already gives a direct solution:

rows = len(df)

Comparisons

ApproachReturnsBest useNotes
df.shape[0]Number of rowsExplicit row countVery common and clear
len(df)Number of rowsShort, readable codeAlso very common
df.shape[1]Number of columnsColumn countNot for rows
df.shape(rows, columns) tupleNeed full dimensionsMust index into it
df.count()Non-null values per columnMissing-data analysisNot total row count
df.emptyTrue or FalseCheck if no rowsGood for guard clauses

len(df) vs df.shape[0]

len(df)
  • shorter
  • readable
  • returns rows for DataFrames
df.shape[0]
  • more explicit about dimensions
  • useful when you also care about columns
  • often used alongside df.shape[1]

Both are correct. Choose the one that makes your code easiest to understand.

Take Quiz

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
  • use df.empty when checking whether there are zero rows

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?

Yes. A filtered DataFrame may contain fewer rows.

filtered = df[df["age"] >= 18]
print(len(filtered))

Which is better: len(df) or df.shape[0]?

Neither is universally better. Use len(df) for brevity and df.shape[0] when you want to be explicit about rows.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more