FAQ: Modifying DataFrames - Applying a Lambda to a Column

This community-built FAQ covers the “Applying a Lambda to a Column” exercise from the lesson “Modifying DataFrames”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Data Science

Data Analysis with Pandas

FAQs on the exercise Applying a Lambda to a Column

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Why can’t we do it in one go as well as in the example? I would have assumed this:
df[‘Last Name’]= df.name.apply(lambda x: x.split()[-1])
should work just as well but it doesn’t.
Is it only because we want the lambda function to have a certain name?
my table doesn’t get altered if i run this code, though

edit: nevermind, it works and my table does get altered. only after i’ve looked at the solution, though, because the exercise was blocking it before i think and giving me strange error messages.

4 Likes

I had the same problem. After I looked at the solution, it seemed one has to break it down into two steps

Why does the lambda used in the solution not require a variable passed to it as lambda functions required in previous examples?

The solution just uses the lambda “get_last_name” as follows:
df[‘last_name’] = df.name.apply(get_last_name)

I had assumed the lambda would need something passed to it like what I tried below:
#df[‘last_name’] = df.apply(get_last_name(df.name))