yangyang
yangyang

Reputation: 531

How to perform multiple if condition in python

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

Upvotes: 1

Views: 62

Answers (3)

Ch3steR
Ch3steR

Reputation: 20669

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")

Upvotes: 1

BernardL
BernardL

Reputation: 5434

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

Upvotes: 0

Pinyi Wang
Pinyi Wang

Reputation: 862

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'))

Upvotes: 2

Related Questions