implementation of multiple if else condition in pandas data frame

Viewed 85

My data frame is -

id       score
1          50
2          88
3          44
4          77
5          93

I want my data frame looks like -

id       score      is_good
1          50        low
2          88        high
3          44        low
4          77        medium
5          93        high

i have done the following code -

def selector(row):
    if row['score'] >= 0 and row['score'] <= 50 :
        return "low"
    elif row['score'] > 50 and row['score'] <=80 :
        return "medium"
    else:
        return "high"

x['is_good'] = x.apply(lambda row : selector(x), axis=1)

I think logic is fine but code is not working. May be we can use map function.

3 Answers

This is a good use case for pd.cut:

df['is_good'] = pd.cut(df.score, 
                       [-np.inf,50,80,np.inf], 
                       labels=['low','medium','high'])

print(df)
   id  score is_good
0   1     50     low
1   2     88    high
2   3     44     low
3   4     77  medium
4   5     93    high

You can use, np.where + Series.between

import numpy as np

df['is_good'] = (
    np.where(df.score.between(0, 50), "low",
             np.where(df.score.between(51, 80), "medium", "high"))
)

   id  score is_good
0   1     50     low
1   2     88    high
2   3     44     low
3   4     77  medium
4   5     93    high

There is error in your code because of:

x['is_good'] = x.apply(lambda row : selector(x), axis=1)

should be :

x['is_good'] = x.apply(lambda row : selector(row), axis=1)

It was taking series not rows that's why you got the error.

Related