亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在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 關注
  • 231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號