Skip to content Skip to sidebar Skip to footer

Multiple Conditions On Dataframes

I'm trying to write a new column 'is_good' which is marked 1 if the data sets in 'value' column is between range 1 to 6 and when 'value2' column is in range 5 to 10 if they do not

Solution 1:

I think need double between and chain conditions by & (bitwise and):

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

Or use 4 conditions:

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

Solution 2:

A bit shorter alternative:

In [47]: df['is_good'] = df.eval("1<=value<=6 & 5<=value2<=10").astype(np.int8)

In [48]: df
Out[48]:
    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

Post a Comment for "Multiple Conditions On Dataframes"