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
CodePudding user response:
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)