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 - Check if the index has unique values
In pandas, you can check if an index contains unique values using the is_unique property. This property returns True if all index values are unique, and False if there are duplicates.
Syntax
index.is_unique
Example with Unique Values
Let's create an index with unique values and check if it has unique values ?
import pandas as pd
# Creating an index with unique values
index = pd.Index([50, 40, 30, 20, 10])
# Display the index
print("Pandas Index...")
print(index)
# Check if the index has unique values
print("\nIs the Pandas index having unique values?")
print(index.is_unique)
Pandas Index... Index([50, 40, 30, 20, 10], dtype='int64') Is the Pandas index having unique values? True
Example with Duplicate Values
Now let's see what happens when the index contains duplicate values ?
import pandas as pd
# Creating an index with duplicate values
index_with_duplicates = pd.Index([50, 40, 30, 20, 30])
# Display the index
print("Pandas Index with duplicates...")
print(index_with_duplicates)
# Check if the index has unique values
print("\nIs the Pandas index having unique values?")
print(index_with_duplicates.is_unique)
Pandas Index with duplicates... Index([50, 40, 30, 20, 30], dtype='int64') Is the Pandas index having unique values? False
Practical Use Case
This property is commonly used with DataFrame indexes to ensure data integrity ?
import pandas as pd
# Create a DataFrame with duplicate index values
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Score': [85, 92, 78, 88]}
df = pd.DataFrame(data, index=[1, 2, 2, 3])
print("DataFrame:")
print(df)
print("\nIndex has unique values:", df.index.is_unique)
DataFrame:
Name Score
1 Alice 85
2 Bob 92
2 Charlie 78
3 David 88
Index has unique values: False
Conclusion
The is_unique property is a simple way to verify if a pandas index contains all unique values. This is particularly useful for data validation and ensuring proper indexing in DataFrames.
Advertisements
