Victor Castro
Victor Castro

Reputation: 105

python how to add IF statement in a map function using lambda

I have this following df:

d = {'role': ['admin/tech', 'admin', 'programming/asst/design']}
df = pd.DataFrame(data=d)

enter image description here

My goal is:

enter image description here

In other words, extract everything before the first '/' IF row contains '/'

I came up with:

enter image description here

and now I need to add a IF statement for this function

I tried something like:

enter image description here

But it doesn´t work.

Thanks in advance, I really appreciate suggestions!!

Upvotes: 0

Views: 491

Answers (1)

not_speshal
not_speshal

Reputation: 23146

You don't need a lambda function for what you want to achieve. Try this:

>>> df["role"].str.split("/").str[0]
0          admin
1          admin
2    programming
Name: role, dtype: object

If for whatever reason you still want to use lambda, do this:

>>> df["role"].apply(lambda x: x.split("/")[0])
0          admin
1          admin
2    programming
Name: role, dtype: object

Upvotes: 2

Related Questions