1

I have this excel function where it says:

=IF(id ="pre_stage";"a";IF(id="static";"b";"c"))

I tried to implement this in my python script to create a new column.

df['type'] = df['id'].apply(lambda x: 'a' if x == 'pre_stage' else 'b')

I miss to put the second condition, where if the 'id' is 'static' then the type should be 'b', and other will be 'c'.

How is the script supposed to write?

Thank you

3 Answers 3

2

Instead of using a lambda, you can pass in a function to apply:

def f(x):
    if x == 'pre_stage':
        return 'a'
    elif x == 'static':
        return 'b'
    return 'c'

df['type'] = df['id'].apply(f)

You can also use a dictionary:

d = {'pre_stage': 'a', 'static': 'b'}
df['type'] = df['id'].apply(lambda x: d.get(x, 'c'))
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a mapping and use pd.Series.map here.

mapping = {"pre_stage": "a", "static": "b"}
df["type"] = df["id"].map(mapping).fillna("c")

You can use np.select here.

condlist = [df["id"].eq("pre_stage"), df["id"].eq("static")]
choicelist = ["a", "b"]
df["type"] = np.select(condlist, choicelist, "c")

Comments

0

If your conditions are going to be nested, its better to define a function for it. It also helps to make your code clearer.

import pandas as pd

df = pd.DataFrame({'type':['pre-stage','static','not-related']})

def func(x):
    if x == 'pre-stage':
        return 'a'
    elif x == 'static':
        return 'b'
    return 'c'

Result:

df['type'].apply(func) #as example, you can assign it to the frame as you did

>>
0    a
1    b
2    c
Name: type, dtype: object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.