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 - Check whether the two Index objects have similar object attributes and types
To check whether two Index objects have similar object attributes and types in Pandas, use the identical() method. This method returns True if both Index objects have the same elements, data types, and metadata.
Syntax
index1.identical(index2)
Where index1 and index2 are the Index objects to compare.
Example with Identical Index Objects
Let's create two identical Index objects and check if they have similar attributes and types −
import pandas as pd
# Creating identical Index objects
index1 = pd.Index([15, 25, 35, 45, 55])
index2 = pd.Index([15, 25, 35, 45, 55])
# Display the indexes
print("Pandas Index1...\n", index1)
print("Pandas Index2...\n", index2)
# Check if they are identical
print("\nAre the two Index objects identical?")
print(index1.identical(index2))
Pandas Index1... Index([15, 25, 35, 45, 55], dtype='int64') Pandas Index2... Index([15, 25, 35, 45, 55], dtype='int64') Are the two Index objects identical? True
Example with Different Data Types
Now let's see what happens when Index objects have the same values but different data types −
import pandas as pd
# Creating Index objects with different data types
index1 = pd.Index([1, 2, 3, 4, 5]) # int64 by default
index2 = pd.Index([1.0, 2.0, 3.0, 4.0, 5.0]) # float64
print("Index1 dtype:", index1.dtype)
print("Index2 dtype:", index2.dtype)
print("\nAre they identical?", index1.identical(index2))
Index1 dtype: int64 Index2 dtype: float64 Are they identical? False
Example with Different Values
Here's an example with Index objects having different values −
import pandas as pd
# Creating Index objects with different values
index1 = pd.Index([10, 20, 30])
index2 = pd.Index([10, 20, 40])
print("Index1:", index1.tolist())
print("Index2:", index2.tolist())
print("\nAre they identical?", index1.identical(index2))
Index1: [10, 20, 30] Index2: [10, 20, 40] Are they identical? False
Key Points
- The
identical()method checks for exact equality including data types, values, and metadata - Returns
Trueonly when both Index objects are completely identical - Different data types (e.g., int64 vs float64) will result in
False - Different values will also result in
False
Conclusion
Use index1.identical(index2) to check if two Pandas Index objects are completely identical in terms of values, data types, and metadata. This method provides a strict comparison for Index objects.
