1

I want to include a variable to a lambda function. I want to replace sales with a variable that I can assign at the beginning of my script so that I don't have to search for this lambda function deep in my code everytime I want to change the metric being measured.

This is the current approach without assigning a variable.

df = (df_raw.rename(columns = {"col1" : "col2", "col3":"col4"})
             .assign(day = lambda x: pd.to_datetime(x.day),
                     orders = lambda x: x.sales.astype(int)

When I try assigning sales to a variable it does not work.

metric = "sales"
kpi = ("lambda x: x." + metric + ".astype(int)")

df = (df_raw.rename(columns = {"col1" : "col2", "col3":"col4"})
             .assign(day = lambda x: pd.to_datetime(x.day),
                     orders = kpi

Is there a better way of doing this? This provides an error when attempting this

1 Answer 1

1

You are not defining a lambda function, but a simple string. This won't lead to execution of a function but assignment of the literal string.

Use:

metric = "sales"
kpi = lambda x: x[metric].astype(int)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.