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 Transpose of the index
In Pandas, the index.T property returns the transpose of an index. For a one-dimensional index, the transpose is the index itself since there's only one dimension.
Syntax
index.T
Creating a Pandas Index
Let's start by creating a simple Pandas Index ?
import pandas as pd
# Creating the index
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])
# Display the index
print("Pandas Index:")
print(index)
Pandas Index: Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')
Using the T Property
Now let's use the T property to get the transpose of the index ?
import pandas as pd
# Creating the index
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])
# Display the original index
print("Original Index:")
print(index)
# Display the transpose of the index
print("\nTranspose of the Index:")
print(index.T)
# Check if they are the same object
print("\nAre they the same object?", index is index.T)
Original Index: Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object') Transpose of the Index: Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object') Are they the same object? True
Why Transpose Returns the Same Index
For a one-dimensional Index, the transpose operation returns the same index because:
- A 1D index has only one dimension
- Transposing a single dimension results in the same structure
- The
Tproperty returns the same object reference
MultiIndex Transpose
The transpose operation becomes more meaningful with MultiIndex ?
import pandas as pd
# Creating a MultiIndex
multi_index = pd.MultiIndex.from_tuples([
('A', 1), ('A', 2), ('B', 1), ('B', 2)
], names=['Letter', 'Number'])
print("Original MultiIndex:")
print(multi_index)
print("\nTranspose of MultiIndex:")
print(multi_index.T)
Original MultiIndex:
MultiIndex([('A', 1),
('A', 2),
('B', 1),
('B', 2)],
names=['Letter', 'Number'])
Transpose of MultiIndex:
MultiIndex([('A', 1),
('A', 2),
('B', 1),
('B', 2)],
names=['Letter', 'Number'])
Conclusion
The index.T property returns the transpose of a Pandas Index. For one-dimensional indexes, it returns the same index object since transposing a single dimension has no effect.
Advertisements
