Home > Blockchain >  How can I increase the efficiency of my code (for loop)?
How can I increase the efficiency of my code (for loop)?

Time:08-26

def assignGroup(row):
    if row["E114"]=="Very good":
        return 1
    elif row['E114']=="Fairly good":
        return 2
    elif row['E114'] =="Bad":
        return 3
    elif row['E114'] =="Very bad":
        return 4
    else:
        return np.nan

outcome["leader"]=outcome.apply(assignGroup,axis=1)

CodePudding user response:

outcome["leader"] = outcome["E114"].map({
    "Very good" : 1,
    "Fairly good": 2,
    "Bad": 3,
    "Very bad": 4
})

CodePudding user response:

Use numpy's where:

import numpy as np
outcome["leader"] = np.where(outcome["E114"] == "Very good", 1, outcome["leader"])
outcome["leader"] = np.where(outcome["E114"] == "Fairly goo", 2, outcome["leader"])
outcome["leader"] = np.where(outcome["E114"] == "Bad", 3, outcome["leader"])
outcome["leader"] = np.where(outcome["E114"] == "Very bad", 4, outcome["leader"])

In Python loops should be last resource

  • Related