How to get boolean value in column based on a range in pandas

Viewed 1450
cf1p2['Age Check'] = (cf1p2['Age']>18 & cf1p2['Age']<60)

I want to check if cf1p2['Age'] is between 18 and 60 and need a result in cf1p2['Age Check'] column

The current code is giving the following error.

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

4 Answers

Hello i came with a solution:

df['Age Check'] = np.where(df['age']>=18 & df['age']<=60, 'yes', 'no')

Let me know if helped!!

Use Series.between:

cf1p2['Age Check'] = cf1p2['Age'].between(18, 60, inclusive=False)

You own solution should also work if you add some parenthesis around your conditions:

cf1p2['Age Check'] = (cf1p2['Age'] > 18) & (cf1p2['Age'] < 60)

Considering this example:

df:

    A   B   C   D   E   F   G
0   52  41  23  53  22  22  39
1   48  49  58  48  45  57  32
2   38  49  48  25  32  22  27
3   46  34  43  52  50  32  30
4   59  47  49  22  53  31  38
5   49  49  58  37  28  31  34
6   31  29  28  41  39  36  47
7   34  55  52  39  32  25  55
8   34  21  48  22  22  53  42
9   44  23  57  52  29  54  43

df['age_check'] = (df['A'] > 58) & (df['A'] < 60)
df

Result:

A   B   C   D   E   F   G   age_check
0   52  41  23  53  22  22  39  False
1   48  49  58  48  45  57  32  False
2   38  49  48  25  32  22  27  False
3   46  34  43  52  50  32  30  False
4   59  47  49  22  53  31  38  True
5   49  49  58  37  28  31  34  False
6   31  29  28  41  39  36  47  False
7   34  55  52  39  32  25  55  False
8   34  21  48  22  22  53  42  False
9   44  23  57  52  29  54  43  False

Instead of

cf1p2['Age Check'] = (cf1p2['Age']>18 & cf1p2['Age']<60)

it should be

cf1p2['Age Check'] = (cf1p2['Age']>18) & (cf1p2['Age']<60)

You missed a pair of brackets to separate the two booleans. Try: cf1p2['Age Check'] = (cf1p2['Age']>18) & (cf1p2['Age']<60)

Related