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
Python Pandas - Return a tuple of the shape of the underlying data
To return a tuple of the shape of the underlying data, use the index.shape property in Pandas. The shape property returns the dimensions of the Index as a tuple.
Syntax
index.shape
This property returns a tuple where the first element represents the number of elements in the Index.
Creating a Basic Index
Let's start by creating a Pandas Index and examining its shape ?
import pandas as pd
# Creating the index
index = pd.Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'])
# Display the index
print("Pandas Index...")
print(index)
# Return a tuple of the shape of the underlying data
print("\nShape of the Index:")
print(index.shape)
Pandas Index... Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object') Shape of the Index: (5,)
Shape with Different Index Types
The shape property works with various types of Index objects ?
import pandas as pd
# Numeric Index
numeric_index = pd.Index([10, 20, 30, 40])
print("Numeric Index shape:", numeric_index.shape)
# RangeIndex
range_index = pd.RangeIndex(0, 10, 2)
print("Range Index shape:", range_index.shape)
# DatetimeIndex
date_index = pd.date_range('2024-01-01', periods=3)
print("DateTime Index shape:", date_index.shape)
Numeric Index shape: (4,) Range Index shape: (5,) DateTime Index shape: (3,)
Understanding the Output
The shape property returns a tuple containing one element − the length of the Index. For a one-dimensional Index with 5 elements, the shape is (5,).
| Index Type | Elements | Shape |
|---|---|---|
| String Index | 5 | (5,) |
| Numeric Index | 4 | (4,) |
| Range Index | 5 | (5,) |
Conclusion
The index.shape property provides a quick way to determine the dimensions of a Pandas Index. It returns a tuple where the first element represents the number of items in the Index, making it useful for understanding data structure dimensions.
