Python | Pandas Index.drop_duplicates ()

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas Index.drop_duplicates() function return Index with duplicate values removed. The function provides the flexibility to choose which duplicate value to be retained. We can drop all duplicate values from the list or leave the first/last occurrence of the duplicated values.

Syntax: Index.drop_duplicates(labels, errors=’raise’)

Parameters :
keep : {‘first’, ‘last’, False}, default ‘first’
-> ‘first’ : Drop duplicates except for the first occurrence.
-> ‘last’ : Drop duplicates except for the last occurrence.
-> False : Drop all duplicates.

Returns : deduplicated : Index

Example #1: Use Index.drop_duplicates() function to drop all the occurrences of the duplicate value except the first occurrence.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index([10, 11, 5, 5, 22, 5, 3, 11])
  
# Print the Index
idx

Выход :

Let’s drop all occurrences of duplicate value in the Index except the first occurrence.

# drop all duplicate occurrences of the
# labels and keep the first occurrence
idx.drop_duplicates(keep ="first")

Output :

As we can see in the output, the Index.drop_duplicate() function has dropped duplicate occurrence of the labels in the Index.
 
Example #2: Use Index.drop_duplicate() function to drop all duplicate occurrence of the label. Do not keep any duplicated values in the Index.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index([10, 11, 5, 5, 22, 5, 3, 11])
  
# Print the Index
idx

Выход :

Let’s drop all occurrences of duplicate value in the Index.

# drop all duplicate occurrences of the labels
idx.drop_duplicates(keep = False)

Выход :

Как видно из выходных данных, все повторяющиеся значения были удалены из индекса.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.