为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

九州编程 2023-12-20 19:43:28
我有这个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”。剧本应该怎么写?谢谢
查看完整描述

3 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

您可以传入一个函数来代替使用 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'))


查看完整回答
反对 回复 2023-12-20
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

您可以在此处创建映射并使用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")


查看完整回答
反对 回复 2023-12-20
?
catspeake

TA贡献1111条经验 获得超0个赞

如果您的条件要嵌套,最好为其定义一个函数。它还有助于使您的代码更清晰。


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'

结果:


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


查看完整回答
反对 回复 2023-12-20
  • 3 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信