Home > OS >  How to optimize my aggregation code ? (Python)
How to optimize my aggregation code ? (Python)

Time:07-13

In order to continue to learn and progress, I am wondering about this code :

def replace_titles(x) :
    title = x['Title']
    if title in ['Dr'] : # Dr to Mr or Mrs
        return 'Mr' if x['Sex'] == 'male' else 'Mrs'
    elif title in ['Don', 'Sir', 'Capt', 'Col', 'Major', 'Rev', 'Jonkheer', 'Mr'] : # Male titles to Mr or Children
        return 'Children' if x['Age'] < 14.5 else 'Mr'
    elif title in ['Master'] : # Master to Children
        return 'Children'
    elif title in ['Lady', 'Countess', 'Dona', 'Mme', 'Miss', 'Mlle', 'Ms', 'Mrs'] : # Female titles to Children or Mrs
        return 'Children' if x['Age'] < 14.5 else 'Mrs'
    else :
        return title

I want to aggregate titles into more meaningful categories and list all the children < 14.5 years.

How do you think I can optimize this code ? (shorter and more efficient)

Maybe with match-case in Python 3.10.x ?

Thank you

CodePudding user response:

if you want it shorter maybe you could do it in just one line with ternary conditional operator

def replace_titles(x):
    title = x['Title']
    return 'Children' if x['Age'] < 14.5 else 'Mr' if x['Sex'] == 'male' and title in ['Dr', 'Don', 'Sir', 'Capt', 'Col', 'Major', 'Rev', 'Jonkheer', 'Mr'] else 'Mrs' if title in ['Lady', 'Countess', 'Dona', 'Mme', 'Miss', 'Mlle', 'Ms', 'Mrs'] else title
  • Related