Python | Панды Series.reindex_like ()

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

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает как целочисленное, так и основанное на метках индексирование и предоставляет множество методов для выполнения операций с индексом.

Pandas Series.reindex_like() function return an object with matching indices as other object. It conform the object to the same index on all axes.

Syntax: Series.reindex_like(other, method=None, copy=True, limit=None, tolerance=None)

Parameter :
other : Its row and column indices are used to define the new indices of this object.
method : Method to use for filling holes in reindexed DataFrame.
copy : Return a new object, even if the passed indexes are the same.
limit : Maximum number of consecutive labels to fill for inexact matches.
tolerance : Maximum distance between original and new labels for inexact matches.

Returns : Series or DataFrame

Example #1: Use Series.reindex_like() function to reindex the given series object based on the other object.

# importing pandas as pd
import pandas as pd
  
# Creating the first Series
sr1 = pd.Series([10, 25, 3, 11, 24, 6])
  
# Create the Index
index_ = ["Coca Cola", "Sprite", "Coke", "Fanta", "Dew", "ThumbsUp"]
  
# set the index
sr1.index = index_
  
# Print the series
print(sr1)
  
# Creating the second Series
sr2 = pd.Series([10, 25, 3, 11, 24, 6, 25, 45])
  
# Create the Index
index_ = ["Coca Cola", "Sprite", "Coke", "Fanta",
            "Dew", "ThumbsUp", "Mirinda", "Appy"]
  
# set the index
sr2.index = index_
  
# Print the series
print(sr2)

Выход :

Now we will use Series.reindex_like() function to reindex the sr2 series object based on sr1.

# reindex sr2 using sr1
result = sr2.reindex_like(sr1)
  
# Print the result
print(result)

Выход :


As we can see in the output, the Series.reindex_like() function has successfully reindexed sr2 object using sr1. Notice for the extra labels has been dropped.

Example #2 : Use Series.reindex_like() function to reindex the given series object based on the other object.

# importing pandas as pd
import pandas as pd
  
# Creating the first Series
sr1 = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio"])
  
# Create the Index
index_ = ["City 1", "City 2", "City 3", "City 4", "City 5"
  
# set the index
sr1.index = index_
  
# Print the series
print(sr1)
  
# Creating the second Series
sr2 = pd.Series(["New York", "Toronto", "Lisbon", "Rio"])
  
# Create the Index
index_ = ["City 1", "City 3", "City 4", "City 5"
  
# set the index
sr2.index = index_
  
# Print the series
print(sr2)

Выход :

Now we will use Series.reindex_like() function to reindex the sr2 series object based on sr1.

# reindex sr2 using sr1
result = sr2.reindex_like(sr1)
  
# Print the result
print(result)

Выход :

As we can see in the output, the Series.reindex_like() function has successfully reindexed sr2 object using sr1. Notice for the newer additions NaN values has been used.

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

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