0
0
PandasHow-ToBeginner · 3 min read

How to Use size in pandas: Syntax and Examples

In pandas, size returns the total number of elements in a DataFrame or Series. For a DataFrame, it equals the number of rows multiplied by columns, and for a Series, it equals the number of elements.
📐

Syntax

The size attribute is used without parentheses because it is a property, not a method. It can be applied to both DataFrame and Series objects.

  • DataFrame.size: Returns total elements (rows × columns).
  • Series.size: Returns total elements in the series.
python
df.size
series.size
💻

Example

This example shows how to use size on a DataFrame and a Series to get the total number of elements.

python
import pandas as pd

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)

print('DataFrame size:', df.size)  # 3 rows * 2 columns = 6

series = pd.Series([10, 20, 30, 40])
print('Series size:', series.size)  # 4 elements
Output
DataFrame size: 6 Series size: 4
⚠️

Common Pitfalls

A common mistake is confusing size with shape or len(). size gives total elements, while shape gives dimensions and len() gives number of rows for DataFrames.

Also, size is an attribute, so do not use parentheses like df.size().

python
import pandas as pd

df = pd.DataFrame({'X': [1, 2], 'Y': [3, 4]})

# Wrong: calling size as a method
# print(df.size())  # This will raise a TypeError

# Correct usage
print(df.size)  # Outputs 4

# Difference from shape and len
print(df.shape)  # Outputs (2, 2)
print(len(df))   # Outputs 2
Output
4 (2, 2) 2
📊

Quick Reference

Summary of related pandas attributes:

AttributeDescriptionExample Output
sizeTotal number of elements (rows × columns)6 for 3x2 DataFrame
shapeTuple of (rows, columns)(3, 2)
len()Number of rows in DataFrame or elements in Series3 for DataFrame, 4 for Series

Key Takeaways

size returns total elements in DataFrame or Series.
size is an attribute, not a method; do not use parentheses.
size differs from shape and len() in what it returns.
Use size to quickly find total data points in your pandas object.