Применение лямбда-функций к Pandas Dataframe

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

В Pandas у нас есть свобода добавлять при необходимости различные функции, такие как лямбда-функция, функция сортировки и т. Д. Мы можем применить лямбда-функцию как к столбцам, так и к строкам фрейма данных Pandas.

Example 1: Applying lambda function to single column using Dataframe.assign()

Python3

# importing pandas library
import pandas as pd
   
# creating and initializing a list
values= [["Rohan",455],["Elvish",250],["Deepak",495],
         ["Soni",400],["Radhika",350],["Vansh",450]] 
  
# creating a pandas dataframe
df = pd.DataFrame(values,columns=["Name","Total_Marks"])
  
# Applying lambda function to find 
# percentage of "Total_Marks" column 
# using df.assign()
df = df.assign(Percentage = lambda x: (x["Total_Marks"] /500 * 100))
  
# displaying the data frame
df

Выход :

В приведенном выше примере лямбда-функция применяется к столбцу Total_Marks, и с его помощью формируется новый столбец Percentage.

Example 2: Applying lambda function to multiple columns using Dataframe.assign()

Python3

# importing pandas library
import pandas as pd
  
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
               [45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90],
               [51, 2.3, 111]]
  
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=["Field_1", "Field_2", "Field_3"])
  
# Applying lambda function to find 
# the product of 3 columns using 
# df.assign()
df = df.assign(Product=lambda x: (x["Field_1"] * x["Field_2"] * x["Field_3"]))
  
# printing dataframe
df

Выход :

В приведенном выше примере лямбда-функция применяется к 3 столбцам, то есть «Поле_1», «Поле_2» и «Поле_3».

Example 3: Applying lambda function to single row using Dataframe.apply()

Python3



# importing pandas and numpy libraries
import pandas as pd
import numpy as np
  
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
               [45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90], 
               [51, 2.3, 111]]
  
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=["Field_1", "Field_2", "Field_3"],
                  index=["a", "b", "c", "d", "e", "f", "g"])
  
  
# Apply function numpy.square() to square
# the values of one row only i.e. row 
# with index name "d"
df = df.apply(lambda x: np.square(x) if x.name == "d" else x, axis=1)
  
  
# printing dataframe
df

Выход :

В приведенном выше примере лямбда-функция применяется к строке, начинающейся с 'd', и, следовательно, квадрат всех значений ей соответствует.

Example 4: Applying lambda function to multiple rows using Dataframe.apply()

Python3

# importing pandas and numpylibraries
import pandas as pd
import numpy as np
  
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
               [45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90],
               [51, 2.3, 111]]
  
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=["Field_1", "Field_2", "Field_3"],
                  index=["a", "b", "c", "d", "e", "f", "g"])
  
  
# Apply function numpy.square() to square 
# the values of 3 rows only i.e. with row
# index name "a", "e" and "g" only
df = df.apply(lambda x: np.square(x) if x.name in [
              "a", "e", "g"] else x, axis=1)
  
# printing dataframe
df

Выход :

В приведенном выше примере лямбда-функция применяется к 3 строкам, начинающимся с «a», «e» и «g».

Example 5: Applying the lambda function simultaneously to multiple columns and rows

Python3

# importing pandas and numpylibraries
import pandas as pd
import numpy as np
  
# creating and initializing a nested list
values_list = [[1.5, 2.5, 10.0], [2.0, 4.5, 5.0], [2.5, 5.2, 8.0],
               [4.5, 5.8, 4.8], [4.0, 6.3, 70], [4.1, 6.4, 9.0],
               [5.1, 2.3, 11.1]]
  
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=["Field_1", "Field_2", "Field_3"],
                  index=["a", "b", "c", "d", "e", "f", "g"])
  
  
# Apply function numpy.square() to square 
# the values of 2 rows only i.e. with row
# index name "b" and "f" only
df = df.apply(lambda x: np.square(x) if x.name in ["b", "f"] else x, axis=1)
  
# Applying lambda function to find product of 3 columns
# i.e "Field_1", "Field_2" and "Field_3"
df = df.assign(Product=lambda x: (x["Field_1"] * x["Field_2"] * x["Field_3"]))
  
  
# printing dataframe
df

Выход :

В этом примере лямбда-функция применяется к двум строкам и трем столбцам.

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

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