python使用多个条件创建一个新列

时间:2019-12-29 22:18:46

标签: python pandas multiple-conditions

我只是从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"

有什么想法吗?我被卡住了。

4 个答案:

答案 0 :(得分:1)

i

您也可以使用pd.cut

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"

答案 1 :(得分: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"

答案 2 :(得分:0)

您可以对熊猫数据框使用lambda函数和apply

我创建了一个虚拟数据文件:

bmi,height
20,72
22,73
26,77
5,66
13,60

导入数据文件

df = pd.read_csv('data.txt', header=0)

像创建NaN一样创建了一个列(但不必这样做)

df["oms"] = np.nan

然后使用lambda将“ bmi”列与某些条件进行比较

df['oms'] = df['bmi'].apply(lambda x: 'slim' if x < 18.5 else ('normal' if x<25 else ('overweight' if x<30 else 'obese')))

数据看起来像这样

print(df.head())

   bmi  height     oms
0   20      72  normal
1   22      73   obese
2   26      77   obese
3    5      66  skinny
4   13      60  skinny

答案 3 :(得分:0)

使用numpy.select,我喜欢这种选择,因为它用途广泛,您可以轻松添加或删除条件。

import numpy as np

condlist = [df["IMC"] <= 18,
           (df["IMC"] >= 18.5) & (df['IMC'] <25),
           (df["IMC"] >= 25) & (df['IMC'] <=30),
            df["IMC"] > 30]

condchoice = ["slim", "normal", "overweight", "obese"]

df["oms"] = np.select(condlist, condchoice)