如何在python中执行多个if条件

我有这个Excel函数,它说:

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

我尝试在我的 python 脚本中实现这一点来创建一个新列。

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

我错过了第二个条件,如果“id”是“static”,那么类型应该是“b”,其他将是“c”。

剧本应该怎么写?

谢谢


九州编程
浏览 67回答 3
3回答

犯罪嫌疑人X

您可以传入一个函数来代替使用 lambda apply:def f(x):    if x == 'pre_stage':        return 'a'    elif x == 'static':        return 'b'    return 'c'df['type'] = df['id'].apply(f)您还可以使用字典:d = {'pre_stage': 'a', 'static': 'b'}df['type'] = df['id'].apply(lambda x: d.get(x, 'c'))

米琪卡哇伊

您可以在此处创建映射并使用pd.Series.map。mapping = {"pre_stage": "a", "static": "b"} df["type"] = df["id"].map(mapping).fillna("c")你可以np.select在这里使用。condlist = [df["id"].eq("pre_stage"), df["id"].eq("static")] choicelist = ["a", "b"] df["type"] = np.select(condlist, choicelist, "c")

catspeake

如果您的条件要嵌套,最好为其定义一个函数。它还有助于使您的代码更清晰。import pandas as pddf = pd.DataFrame({'type':['pre-stage','static','not-related']})def func(x):    if x == 'pre-stage':        return 'a'    elif x == 'static':        return 'b'    return 'c'结果:df['type'].apply(func) #as example, you can assign it to the frame as you did>>0    a1    b2    cName: type, dtype: object
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python