3 回答

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

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

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
添加回答
舉報