2
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().

Husnain Iqbal
  • 89
  • 1
  • 10
  • kindly post data with expected results. Use this as a guide : https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – sammywemmy Mar 09 '20 at 11:40
  • 1
    `cf1p2['Age Check'] = cf1p2['Age'].between(18, 60, inclusive=False)` – Chris Adams Mar 09 '20 at 11:40
  • try `cf1p2.loc[(cf1p2['Age']>18) & (cf1p2['Age']<60), 'new_col'] = value` you can also use `np.where` basically to turn the dataframe into a true false boolean you need to access or return it as an expression of a dataframe or use a pandas/numpy method that turns a series/dataframe into a boolean – Umar.H Mar 09 '20 at 11:40
  • Does this answer your question? [pandas equivalent of np.where](https://stackoverflow.com/questions/38579532/pandas-equivalent-of-np-where) – Umar.H Mar 09 '20 at 11:42

4 Answers4

2

Hello i came with a solution:

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

Let me know if helped!!

Jovani
  • 27
  • 4
1

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)
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
1

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)
Pygirl
  • 12,969
  • 5
  • 30
  • 43
1

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

tianlinhe
  • 991
  • 1
  • 6
  • 15