Min
Min

Reputation: 528

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 satisfy both condition they are marked 0

I know if you do this,

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

it will fill out 1 or 0 depending on the ranges of value but how would I also consider ranges of value2 when marking 1 or 0.

Is there anyway I can achieve this without numpy?

Thank you in advance!

Upvotes: 4

Views: 71

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210822

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

Upvotes: 1

jezrael
jezrael

Reputation: 862431

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

Upvotes: 5

Related Questions