Python | Панды Index.insert ()

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

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

Pandas Index.insert() function make new Index inserting new item at location. This function also follows Python list.append() semantics for negative values. If the negative value are passed then it start from the other end.

Syntax: Index.insert(loc, item)

Parameters :
loc : int
item : object

Returns : new_index : Index

Example #1: Use Index.insert() function to insert a new value in the Index.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(["Labrador", "Beagle", "Labrador",
                     "Lhasa", "Husky", "Beagle"])
  
# Print the Index
idx

Output :

Now insert ‘Great_Dane’ at the 1st index.

# Inserting a value at the first position in the index.
idx.insert(1, "Great_Dane")

Выход :

As we can see in the output, the Index.insert() function has inserted the passed value at the desired location.
 
Example #2: Use Index.insert() function to insert a value into the Index at the second position from the last in the Index.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(["Labrador", "Beagle", "Labrador",
                     "Lhasa", "Husky", "Beagle"])
  
# Print the Index
idx

Выход :

Now insert ‘Great_Dane’ at the 1st index from the last.

# Inserting a value at the first position in the index.
idx.insert(-1, "Great_Dane")

Выход :

Как мы видим в выходных данных, переданное значение было вставлено в индекс в желаемом месте.

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

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