数据帧的多个条件

Seo*_*Min 3 python dataframe pandas

我正在尝试写一个新列'is_good',如果'value'列中的数据集在1到6之间,并且'value2'列在5到10之间,如果它们不满足这两个条件,则标记为1 它们标记为0

我知道如果你这样做,

df['is_good'] = [1 if (x >= 1 and x <= 6) else 0 for x in df['value']]

它将根据值的范围填充1或0但是在标记1或0时我还将如何考虑值2的范围.

无论如何我有没有numpy可以达到这个目的?

先感谢您!

jez*_*ael 5

我认为需要双重between和链条条件&(按位和):

df = pd.DataFrame({'value':range(13),'value2':range(13)})
df['is_good'] =  (df['value'].between(1,6) & df['value2'].between(5,10)).astype(int)
Run Code Online (Sandbox Code Playgroud)

或使用4个条件:

df['is_good'] =  ((df['value'] >= 1) & (df['value'] <= 6) & 
                   (df['value2'] >= 5) & (df['value'] <= 10)).astype(int) 


print (df)
    value  value2  is_good
0       0       0        0
1       1       1        0
2       2       2        0
3       3       3        0
4       4       4        0
5       5       5        1
6       6       6        1
7       7       7        0
8       8       8        0
9       9       9        0
10     10      10        0
11     11      11        0
12     12      12        0
Run Code Online (Sandbox Code Playgroud)