How to Use shape in pandas to Check DataFrame Size
In pandas, use the
shape attribute on a DataFrame or Series to get its size as a tuple (rows, columns). For example, df.shape returns the number of rows and columns in the DataFrame df.Syntax
The shape attribute returns a tuple representing the dimensions of a pandas DataFrame or Series.
df.shape: Returns (number of rows, number of columns) for a DataFrame.series.shape: Returns (number of elements,) for a Series.
python
df.shape
Example
This example shows how to create a DataFrame and use shape to find its size.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) print('DataFrame shape:', df.shape) # For a Series ages = df['Age'] print('Series shape:', ages.shape)
Output
DataFrame shape: (3, 2)
Series shape: (3,)
Common Pitfalls
Some common mistakes when using shape include:
- Trying to call
shape()as a function instead of using it as an attribute (no parentheses needed). - Expecting
shapeto return a number instead of a tuple. - Confusing the order: the first number is rows, the second is columns.
python
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # Wrong: calling shape as a function try: print(df.shape()) except TypeError as e: print('Error:', e) # Right: use shape as attribute print('Correct shape:', df.shape)
Output
Error: 'tuple' object is not callable
Correct shape: (2, 2)
Quick Reference
| Usage | Description | Example Output |
|---|---|---|
| df.shape | Returns (rows, columns) tuple of DataFrame size | (3, 2) |
| series.shape | Returns (length,) tuple of Series size | (3,) |
| Incorrect: df.shape() | Calling shape as function causes error | TypeError |
| Order of tuple | First element is rows, second is columns | rows=3, columns=2 |
Key Takeaways
Use
shape without parentheses to get DataFrame or Series size.shape returns a tuple: (rows, columns) for DataFrames, (length,) for Series.Remember the first number is rows, the second is columns in DataFrames.
Calling
shape() as a function causes a TypeError.Use
shape to quickly check data size before analysis.