This short tutorial aims to show how you can use Lambda functions
in Python, and especially in Pandas.
Introduction
The following is the basic structure of Lambda functions:
lambda bound_variable
: function_or_expression
Lambda functions can have any number of arguments
but only one expression
, typically in one-line expression. The following is an example of adding the number 5 into variable X.
lambda x: x+5
It is the same as the following function.
def add(x):
return(x+5)
Method 1: Use Lambda function as IIFEs
IIFEs stand for Immediately Invoked Function Expressions. An IIFE is a way to execute functions immediately when they are created. IIFEs are very useful because they don’t pollute the global object. The following is an example of using Lambda functions as IIFEs.
We append ()
to execute that function: (function)()
.
(lambda x: x+5)(10)
15
Method 2: Use Lambda with apply() in Pandas
We can use apply()
to call a lambda function, which will be applied to every row or column of the dataframe and returns a modified version of the original dataframe. If axis = 0
in apply()
, the lambda function will be applied to each column. In contrast, If axis =
1 in apply()
, the lambda function will be applied to each row.
The following example applies a lambda function to each row to create a new column by calculating how old the cars are. The following shows the original data.
import pandas as pd
car_data = {'Brand': ['Tesla', 'Tesla','Tesla','Ford'],
'Location': ['CA', 'CA','NY','MA'],
'Year':[2019,2018,2020,2019]}
car_data=pd.DataFrame(data=car_data)
print(car_data)
Brand Location Year 0 Tesla CA 2019 1 Tesla CA 2018 2 Tesla NY 2020 3 Ford MA 2019
Next is the sample code for using apply()
and lambda
.
car_data["Year_old"]=car_data.apply(lambda x: 2022-x['Year'],axis=1)
print(car_data)
Brand Location Year DateTime Year_old Brand Location Year Year_old 0 Tesla CA 2019 3 1 Tesla CA 2018 4 2 Tesla NY 2020 2 3 Ford MA 2019 3
Method 3: Use filter() and list()
You can use the combination of filter()
, list()
, and lambda
functions to find the elements within a column in Pandas. You can see that the lambda function
and the dataframe column
is connected with a comma ","
.
list(filter(lambda x: x>=2019,car_data['Year']))
[2019, 2020, 2019]
Method 4: Use if-else in Lambda functions
You can use if else
statements in lambda functions in Pandas.
car_data['CA_or_not']=car_data['Location'].apply(lambda x: True if x=='CA' else False)
print(car_data)
Brand Location Year Year_old CA_or_not 0 Tesla CA 2019 3 True 1 Tesla CA 2018 4 True 2 Tesla NY 2020 2 False 3 Ford MA 2019 3 False
The following is another example.
car_data['EV_or_not']=car_data['Brand'].apply(lambda x: 'EV' if x=='Tesla' else 'Not Sure')
print(car_data)
Brand Location Year Year_old CA_or_not EV_or_not 0 Tesla CA 2019 3 True EV 1 Tesla CA 2018 4 True EV 2 Tesla NY 2020 2 False EV 3 Ford MA 2019 3 False Not Sure