如何应用多个if语句?

时间:2019-09-27 18:34:01

标签: python function dataframe

我有一个df,并且想对每行应用以下语句;

IF df['aon'] == 12, recode to 10,  but also change on the same row df['identity'] == 4 and df['NO'] == 2.5 df['HR'] == 110

ELSEIF df['aon'] == 10, recode to 8 .

如果不满足这些条件,我想保持每一行不变。我知道一种解决方法,但我想尽可能采用最有效的方法。

之前;

Aon    Identity    No    HR

11     8.0         3.5   99
12     7.0         3.1   99
21     8.0         2.8   100
12     7.0         1.5   78
31     4.0         1.2   95

之后;

Aon    Identity    No    HR

11     8.0         3.5   99
12     4.0         2.5   110
21     8.0         2.8   100
12     4.0         2.5   110
31     4.0         1.2   95

2 个答案:

答案 0 :(得分:1)

您不清楚您想要什么条件,但是 您可以将逻辑运算和熊猫结合使用,其中函数可以实现您想要的

例如,如果要选择符合以下条件的行 df ['identity'] == 4和df ['NO'] == 2.5 df ['HR'] == 110您可以做到

cond = (df['identity'] == 4) & (df['NO'] == 2.5) & (df['HR'] == 110)

## then you can use the above condition to set value on col1 like this
## this will set 10 to rows not matching the cond
df["col1"] = df["col1"].where(cond, 10)


## this will set 10 to rows matching the cond
df["col1"] = df["col1"].mask(cond, 10)

答案 1 :(得分:0)

这应该可以解决问题。由于您没有Aon等于10的输入数据-我以21为例,因为它存在。

>>> df
   Aon  Identity   No   HR
0   11       8.0  3.5   99
1   12       7.0  3.1   99
2   21       8.0  2.8  100
3   12       7.0  1.5   78
4   31       4.0  1.2   95
>>> df.apply(lambda x: {"Aon": 10, "Identity": 4, "No": 2.5, "HR": 110} if x["Aon"]==12 else ({"Aon": 8, "Identity": x.Identity, "No": x.No, "HR": x.HR} if x["Aon"]==21 else x), axis=1)
    Aon     HR  Identity   No
0  11.0   99.0       8.0  3.5
1  10.0  110.0       4.0  2.5
2   8.0  100.0       8.0  2.8
3  10.0  110.0       4.0  2.5
4  31.0   95.0       4.0  1.2