Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Return the number of bytes in the underlying Index data
The index.nbytes property in Pandas returns the number of bytes consumed by the underlying Index data. This is useful for memory analysis and optimization.
Syntax
index.nbytes
Basic Example
Let's create a simple Index and check its memory usage ?
import pandas as pd
# Creating the index
index = pd.Index([15, 25, 35, 45, 55])
# Display the index
print("Pandas Index...")
print(index)
# Get the bytes in the data
print("\nNumber of bytes:")
print(index.nbytes)
Pandas Index... Index([15, 25, 35, 45, 55], dtype='int64') Number of bytes: 40
Memory Usage with Different Data Types
Different data types consume different amounts of memory ?
import pandas as pd
# Integer Index (int64)
int_index = pd.Index([1, 2, 3, 4, 5])
# Float Index (float64)
float_index = pd.Index([1.0, 2.0, 3.0, 4.0, 5.0])
# String Index
string_index = pd.Index(['A', 'B', 'C', 'D', 'E'])
print("Integer Index bytes:", int_index.nbytes)
print("Float Index bytes:", float_index.nbytes)
print("String Index bytes:", string_index.nbytes)
Integer Index bytes: 40 Float Index bytes: 40 String Index bytes: 40
Complete Example with Index Properties
Here's a comprehensive example showing various Index properties including nbytes ?
import pandas as pd
# Creating the index
index = pd.Index([15, 25, 35, 45, 55])
# Display the index
print("Pandas Index...")
print(index)
# Return an array representing the data in the Index
print("\nArray...")
print(index.values)
# Return a tuple of the shape of the underlying data
print("\nShape of underlying data...")
print(index.shape)
# Get the bytes in the data
print("\nNumber of bytes...")
print(index.nbytes)
# Additional info
print("\nData type:")
print(index.dtype)
print("\nSize (number of elements):")
print(index.size)
Pandas Index... Index([15, 25, 35, 45, 55], dtype='int64') Array... [15 25 35 45 55] Shape of underlying data... (5,) Number of bytes... 40 Data type: int64 Size (number of elements): 5
Key Points
- Each int64 element uses 8 bytes (5 elements × 8 bytes = 40 bytes)
- The nbytes property only counts data bytes, not overhead
- String indices may show different byte calculations due to object storage
- This property is useful for memory profiling large datasets
Conclusion
The index.nbytes property provides the memory footprint of Index data in bytes. Use this for memory optimization and understanding storage requirements of your Pandas Index objects.
Advertisements
