Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make if else commands more effective?

I have a huge dataframe ~100,000 rows. I have this code but it is taking way too long to execute. Is there any way to make this more efficient somehow?

df["Grade Band"] = ""
k5 = ["0","1","2","3","4","5"]
ms = ["6", "7" ,"8"]
hs = ["9","10","11","12"]

for x in df["Grade Roll"]:
        if x == "Other":
            df["Grade Band"] == "Undefined"
        elif x in k5:
            df["Grade Band"] == "K5"
        elif x in ms:
            df["Grade Band"] == "MS"
        elif x in hs:
             df["Grade Band"] == "HS"

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This should be pretty fast:

df.loc[df["Grade Roll"] == "Other", "Grade Roll"] = "Undefined"
df.loc[df["Grade Roll"].isin(k5), "Grade Roll"] = "K5"
df.loc[df["Grade Roll"].isin(ms), "Grade Roll"] = "MS"
df.loc[df["Grade Roll"].isin(hs), "Grade Roll"] = "HS"

If you wanted it to be less repetitive, you could store your arrays in a dict:

d = {
    "K5": ["0","1","2","3","4","5"],
    "MS": ["6", "7" ,"8"],
    "HS": ["9","10","11","12"],
    "Undefined": ["Other"]
}

for k, v in d.items():
    df.loc[df["Grade Roll"].isin(v), "Grade Roll"] = k
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading