Learn
Modifying DataFrames
Applying a Lambda to a Column

In Pandas, we often use lambda functions to perform complex operations on columns. For example, suppose that we want to create a column containing the email provider for each email address in the following table:

Name Email
JOHN SMITH [email protected]
Jane Doe [email protected]
joe schmo [email protected]

We could use the following code with a lambda function and the string method .split():

df['Email Provider'] = df.Email.apply( lambda x: x.split('@')[-1] )

The result would be:

Name Email Email Provider
JOHN SMITH [email protected] gmail.com
Jane Doe [email protected] yahoo.com
joe schmo [email protected] hotmail.com

Instructions

1.

Create a lambda function get_last_name which takes a string with someone’s first and last name (i.e., John Smith), and returns just the last name (i.e., Smith).

2.

The DataFrame df represents the hours worked by different employees over the course of the week. It contains the following columns:

  • 'name': The employee’s name
  • 'hourly_wage': The employee’s hourly wage
  • 'hours_worked': The number of hours worked this week

Use the lambda function get_last_name to create a new column last_name with only the employees’ last name.

Folder Icon

Sign up to start coding

Already have an account?