Python Pandas - Return the Number of dimensions of the underlying data

To return the number of dimensions of the underlying data in a Pandas Index, use the index.ndim property. This property returns an integer representing the dimensionality of the Index.

Basic Usage

First, let's create a simple Index and check its dimensions ?

import pandas as pd

# Create a simple Index
index = pd.Index([15, 25, 35, 45, 55])
print("Pandas Index...")
print(index)
print("\nNumber of dimensions:", index.ndim)
Pandas Index...
Index([15, 25, 35, 45, 55], dtype='int64')

Number of dimensions: 1

Understanding Index Dimensions

Pandas Index objects are always one-dimensional, regardless of their content type. Let's verify this with different Index types ?

import pandas as pd

# Different types of Index
numeric_index = pd.Index([1, 2, 3, 4, 5])
string_index = pd.Index(['A', 'B', 'C', 'D'])
date_index = pd.date_range('2023-01-01', periods=4, freq='D')

print("Numeric Index dimensions:", numeric_index.ndim)
print("String Index dimensions:", string_index.ndim)
print("Date Index dimensions:", date_index.ndim)
Numeric Index dimensions: 1
String Index dimensions: 1
Date Index dimensions: 1

Complete Example

Here's a comprehensive example showing ndim along with related properties ?

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("\nBytes used...")
print(index.nbytes)

# Get the dimensions of the data
print("\nNumber of dimensions...")
print(index.ndim)
Pandas Index...
Index([15, 25, 35, 45, 55], dtype='int64')

Array...
[15 25 35 45 55]

Shape of underlying data...
(5,)

Bytes used...
40

Number of dimensions...
1

Key Points

  • All Pandas Index objects are one-dimensional by design
  • The ndim property always returns 1 for Index objects
  • Use shape to get the actual size of the Index
  • This property is useful for programmatic validation of data structures

Conclusion

The ndim property provides a quick way to verify that an Index object is one-dimensional. While it always returns 1 for Index objects, it's useful for consistency checks and programmatic data structure validation.

Updated on: 2026-03-26T16:14:50+05:30

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements