Python | Pandas Index.difference ()

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

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

Pandas Index.difference() function return a new Index with elements from the index that are not in other.
The function automatically sorts the output if sorting is possible.

Syntax: Index.difference(other)

Parameters :
other : Index or array-like

Returns : difference : Index

Example #1: Use Index.difference() function to find the set difference of a given Index with an array-like object.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index([17, 69, 33, 15, 19, 74, 10, 5])
  
# Print the Index
idx

Выход :

Let’s find the set difference of the given Index with an array-like object

# find the set difference of this Index 
# with the passed array object.
idx.difference([69, 33, 15, 74, 19])

Выход :

Как видно из вывода, функция вернула объект, который содержит только те значения, которые уникальны для индекса idx.

Note that the output object has its element sorted in Increasing order.
 
Example #2: Use Index.difference() function to find the set difference of two Indexes.

# importing pandas as pd
import pandas as pd
  
# Creating the first Index
idx1 = pd.Index(["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
  
# Creating the second Index
idx2 = pd.Index(["May", "Jun", "Jul", "Aug"])
  
# Print the first and second Index
print(idx1, " ", idx2)

Выход :

Now, let’s find the set difference between two Indexes.

# to find the set differnece
idx1.difference(idx2)

Выход :

Функция вернула установленную разницу idx1 и idx2 . Он содержит только те значения, которые уникальны для индекса idx1. Обратите внимание, что вывод не сортируется.

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

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