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

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

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

Pandas Series.add_prefix() function is used to add prefix to each index labels of the given series object.

Syntax: Series.add_prefix(prefix)

Parameter :
prefix : The string to add before each label.

Returns : Series or DataFrame

Example #1: Use Series.add_prefix() function to add prefix to each index labels in the given series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([34, 5, 13, 32, 4, 15])
  
# Create the Index
index_ = ["Coca Cola", "Sprite", "Coke", "Fanta", "Dew", "ThumbsUp"]
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

Now we will use Series.add_prefix() function to add the string label ‘IPL 2019_’ before each index labels in the given series object.

# add "IPL 2019_" before each index labels
result = sr.add_prefix(prefix = "IPL 2019_")
  
# Print the result
print(result)

Output :

As we can see in the output, the Series.add_prefix() function has successfully added the passed string label before each index labels in the given series object.
 
Example #2 : Use Series.add_prefix() function to add prefix to each index labels in the given series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([51, 10, 24, 18, 1, 84, 12, 10, 5, 24, 0])
  
# Create the Index
# apply yearly frequency
index_ = pd.date_range("2010-10-09 08:45", periods = 11, freq ="Y")
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

Now we will use Series.add_prefix() function to add the string label ‘Date_’ before each index labels in the given series object.

# add "Date_" before each index labels
result = sr.add_prefix(prefix = "Date_")
  
# Print the result
print(result)

Output :

As we can see in the output, the Series.add_prefix() function has successfully added the passed string label before each index labels in the given series object.

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

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