-1

I was trying to mutate a dataframe, using lambda expression but was having trouble indeed.

Firstly, a dataframe was created:

import pandas as pd
d = pd.DataFrame({"name":["aaa", "bbb", "ccc"],
            "usage":[15, 40, 60],
            "status":""})

Then, a function was created to mutate the "status" column:

def func(status, usage):
    if usage >= 50:
        status = "platinum"
    elif usage >= 30:
        status = "gold"
    else:
        status = "none"   

Then a lambda expression was written to execute the mutation:

d["status"] = d.apply(lambda x:
                 func(x["status"], x["usage"]), axis=1)

However, the output shows as this:

name usage status
0 aaa 15 none
1 bbb 40 none
2 ccc 60 none

Here, as the code was written in the function, it was supposed to be "none", "gold", and "platinum" in the "status" column. Would be a great help if the solution is given.

  • this should work if you `return status` in your function (even if there are much better methods for pandas) – mozway Jun 03 '22 at 13:40
  • Solved the problem: `def func(status, usage): if usage > 50: return "platinum" elif usage > 30: return "gold" else: return "none" ` – Janilin Bappi Jun 03 '22 at 13:55

0 Answers0