Python Pandas - Indicate duplicate index values except for the last occurrence

PythonPandasServer Side ProgrammingProgramming

To indicate duplicate index values except for the last occurrence, use the index.duplicated(). Use the keep parameter with the value last.

At first, import the required libraries −

import pandas as pd

Creating the index with some duplicates−

index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])

Display the index −

print("Pandas Index with duplicates...\n",index)

Indicate duplicate index values as True, except the last occurrence. Set the "keep" parameter as "last" −

print("\nIndicating duplicate values except the last occurrence...\n", index.duplicated(keep='last'))

Example

Following is the code −

import pandas as pd

# Creating the index with some duplicates
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])

# Display the index
print("Pandas Index with duplicates...\n",index)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# get the dimensions of the data
print("\nGet the dimensions...\n",index.ndim)

# Indicate duplicate index values as True, except the last occurrence
# Set the "keep" parameter as "last"
print("\nIndicating duplicate values except the last occurrence...\n", index.duplicated(keep='last'))

Output

This will produce the following code −

Pandas Index with duplicates...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')

The dtype object...
object

Get the dimensions...
1

Indicating duplicate values except the last occurrence...
[False False True False False]
raja
Updated on 13-Oct-2021 11:39:42

Advertisements