How to Use len() for DataFrame in pandas: Simple Guide
Use
len() on a pandas DataFrame to get the number of rows it contains. For example, len(df) returns the count of rows in the DataFrame df.Syntax
The syntax to use len() with a pandas DataFrame is simple:
len(dataframe): Returns the number of rows in the DataFrame.
This works because a DataFrame's length is defined as its number of rows.
python
len(dataframe)Example
This example shows how to create a DataFrame and use len() to find out how many rows it has.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) row_count = len(df) print(row_count)
Output
3
Common Pitfalls
Some common mistakes when using len() with DataFrames include:
- Expecting
len()to return the number of columns instead of rows. - Using
len()on a DataFrame column (a Series) and confusing it with the DataFrame length.
To get the number of columns, use df.shape[1] instead.
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) # Wrong: expecting columns count wrong = len(df) # This returns rows count, not columns # Right: get columns count right = df.shape[1] print(f"Rows: {len(df)}") print(f"Columns: {right}")
Output
Rows: 2
Columns: 2
Key Takeaways
Use len(dataframe) to get the number of rows in a pandas DataFrame.
len() returns rows count, not columns count.
To get columns count, use dataframe.shape[1].
len() works because DataFrame length is defined as its row count.