[英]python value conditional on two columns
I have the following dataset: 我有以下数据集:
id Rank condition1 condition2 result
1 2 50 0 0
1 2 50 0 0
2 55 50 1 0
2 55 50 1 0
I want to make the result column to 1 conditional on the two columns condition 1 and condition 2. 我想根据两列条件1和条件2将结果列设置为1。
The Result should become 1 if rank <= condition 1 AND if condition2 = 0
如果rank <= condition 1 AND if condition2 = 0
结果应为1
id Rank condition1 condition2 result
1 2 50 0 1
1 2 50 0 1
2 55 50 1 0
2 55 50 1 0
I have tried the following code but get "invalid syntax". 我试过下面的代码,但得到“无效的语法”。
df["result"][df[condition2] = 0 & df["Rank"]<= df["condition1"]] = 1
Can somebody help me in finding the error? 有人可以帮助我找到错误吗? I know how to make this command conditional on one condition, but I do not know how to incorporate the second condition with the AND command. 我知道如何使此命令成为一个条件的条件,但是我不知道如何将第二个条件与AND命令结合在一起。
You need to use ==
for equality checks, the single =
is for assignments not for comparisons: 您需要将==
用于相等性检查,单个=
用于分配而不是比较:
df["result"][(df['condition2'] == 0) & (df["Rank"]<= df["condition1"])] = 1
You also forgot the '
for condition2
and I included some parenthesis to seperate the conditions because &
has higher precedence than ==
or <=
. 您也忘了'
for condition2
并且我加上了一些括号来分隔条件,因为&
优先级高于==
或<=
。
Pandas also provides methods for comparisons ( eq
and le
in this case), so you could also use: Pandas还提供了比较方法le
在这种情况下为eq
和le
),因此您还可以使用:
df["result"][df['condition2'].eq(0) & df['Rank'].le(df['condition1'])] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.