Lambda Function

Lambda function

1. Apply Lambda function to a column

We can use lambda functions to perform complex operations on columns.

Example 1

We can create a new column last_name from this table

nameemail
0Jane Doejdoe@gmail.com
1John Smithjsmith@gmail.com
2Lara Lanelaral@gmail.com
get_last_name = lambda x: x.split()[-1]
df['last_name'] = df.name.apply(get_last_name)
nameemaillast_name
0Jane Doejdoe@gmail.comDoe
1John Smithjsmith@gmail.comSmith
2Lara Lanelaral@gmail.comLane

Example 2

We calculate the 25th percent for shoe price for each shoe_color:

cheap_shoes = orders.groupby('shoe_color').price.apply(lambda x: np.percentile(x, 25)).reset_index()

print(cheap_shoes)
shoe_colorprice
0black130.0
1brown248.0
2navy200.0
3red157.0
4white188.0

2. Apply Lambda to a row

To access particular values of the row, we use the syntax row.column_name or row[‘column_name’].

If we use apply without specifying a single column and add the argument axis=1, the input to our lambda function will be an entire row, not a column

df['Price with Tax'] = df.apply(lambda row:
     row['Price'] * 1.075
     if row['Is taxed?'] == 'Yes'
     else row['Price'],
     axis=1
)