Skip to content
Think & Reflect · Q3

Q.Can you write a program to count the number of rows and columns in a DataFrame?

West Bengal WbchseTextbookSubjective· 2mImportance★★★★★est
58% · 22/38 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Use the .shape attribute of a DataFrame to get a tuple (rows, columns), or use len(df) for rows and len(df.columns) for columns separately.

This is a code / query task — the question asks for a program that counts rows and columns in a DataFrame. The core idea is that a DataFrame in pandas has a built-in attribute .shape that returns exactly this information as a tuple. This is the most direct and Pythonic way to get both dimensions at once.

The .shape attribute is a property, not a method — so no parentheses are needed. It returns (number_of_rows, number_of_columns). If you need the values separately, you can unpack them into two variables.

Here's the complete, runnable solution:

import pandas as pd

# Sample DataFrame (you can replace this with any DataFrame)
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'Age': [25, 30, 35, 28],
    'City': ['New York', 'London', 'Paris', 'Tokyo']
}
df = pd.DataFrame(data)

# Method 1: Using .shape (returns a tuple)
rows, cols = df.shape
print(f"Number of rows: {rows}")
print(f"Number of columns: {cols}")

# Method 2: Using len() for rows and .columns for columns
print(f"Rows (using len): {len(df)}")
print(f"Columns (using len(df.columns)): {len(df.columns)}")

Expected output:

Number of rows: 4
Number of columns: 3
Rows (using len): 4
Columns (using len(df.columns)): 3

Key lines explained:

  • df.shape — This is the most efficient way. It's a property that pandas computes lazily (it doesn't iterate through the data), so it's O(1) in time. The tuple (4, 3) tells us there are 4 rows and 3 columns. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.