Image for post
Image for post

How to Apply Lambda & Apply Function in a Pandas Dataframe

Three strategies for creating a new Pandas DataFrame column from a calculation, and a comparison of performance

Image for post
Image for post

Table of Contents:

Strategy 1: Write a function, and apply that function.

def covid_before_age(start_date) :
if start_date < pd.to_datetime('3/6/2020') :
covid_status = "before"
else :
covid_status = "after"
return covid_status
df['covid_status'] = df.start_date.apply(covid_before_age)
df.shape
Image for post
Image for post
Image for post
Image for post

Strategy 2: Write a Lambda, and apply that Lambda

df['covid_status'] = df.start_date.apply(lambda x : x >= datetime.date(2020,3,6))
df.shape
Image for post
Image for post
Image for post
Image for post

Strategy 1.2: Write a better function, and apply that function.

def covid_status_datetime(start_date) :
if start_date < datetime.date(2020,3,6) :
covid_status = "before"
else :
covid_status = "after"
return covid_status
df['covid_status_datetime'] = df.start_date.apply(covid_status_datetime)
Image for post
Image for post

Written by

Documentation and tutorials on Python, Programming, and Data Analysis. FPL Addict. Occasionally writing about biohacking, PMing, and food.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store