python使用多个条件创建新列

问题描述 投票:0回答:2

我只是从Python开始,我有很多主题及其BMI体重指数(还有更多数据)。我需要创建一个新列(称为OMS),在其中可以说明它们是否为“正常”,“超重”,“肥胖”等。

但是我只是找不到正确的方法。我尝试了np.when,但仅在2个条件下有效。

我尝试过if,elif,else,但没有成功,也有:

df['oms'] = np.nan

df['oms'].loc[(df['IMC'] <=18.5 )] = "slim"

df['oms'].loc[(df['IMC'] >= 18.5) & (df['IMC'] <25 )] = "normal"

df['oms'].loc[(df['IMC'] >= 25) & (df['IMC'] <=30 )] = "overweight"

df['oms'].loc[(df['IMC'] > 30)] = "obese"

任何想法?我被卡住了。

python multiple-conditions
2个回答
0
投票
df.loc[(df['IMC'].lt(18.5), 'oms'] = "slim"
df.loc[(df['IMC'].ge(18.5) & df['IMC'].lt(25), 'oms'] = "normal"
df.loc[(df['IMC'].ge(25) & df['IMC'].lt(30), 'oms'] = "overweight"
df.loc[(df['IMC'].ge(30), 'oms'] = "obese"

0
投票

也许尝试:

df['oms'] = ""#keep it object dtype

df.loc[(df['IMC'] <=18.5 ), 'oms'] = "slim"
df.loc[(df['IMC'] >= 18.5) & (df['IMC'] <25 ), 'oms'] = "normal"
df.loc[(df['IMC'] >= 25) & (df['IMC'] <=30 ), 'oms'] = "overweight"
df.loc[(df['IMC'] > 30), 'oms'] = "obese"
© www.soinside.com 2019 - 2024. All rights reserved.