Search code examples
pythonpandasoop

How to call a python function based on a pandas column value where the function called returns a dataframe?


I have a pandas dataframe which list items, locations they are sold in, and the models that gave said items the lowest mape out of all models ran.

Here is a sample of what this df looks like.

import pandas as pd
model = ['autoarima', 'prophet', 'TES']
item = ['102354','215898','302584']
MAPE = [46.2, 23.5, 15.6]
location = ['KR_DC', 'KR_DC','KR_DC']
df_dict = {'fcast_item':item, 'location':location, 'mape':MAPE, 'best_model':model}
df = pd.DataFrame.from_dict(df_dict)

I would like to use the value for model to call that model's function which is stored in a class and run the function which returns a dataframe.

For example, if the model is 'TES', then I'd like the following line of code ran:

df = [statmod.stats_models(df).tesa_model(target='corrected_demand', combo = combo, length=length_) for combo in combos]

If the model is autoarima then the following would be ran

df = [statmod.stats_models(df).arima_model(target='corrected_demand', combo = combo, length=length_) for combo in combos]

If it helps, the following will always be the same: df = [statmod.stats_models(df). as well as (target='corrected_demand', combo = combo, length=length_) for combo in combos]. Only the middle, where the model function itself is located would change.

I've never done this type of dynamic coding where a dataframe value calls a line of code to run. Is this possible?


Solution

  • You can try to use Python's built-in exec function, along with f-strings, whenever I have to do some dynamic coding like I use this (I'm not an expert Python programmer, so there might be a more efficient way to solve this type of problem)

    Here is an example code:

    exec(f"new_dataframe = statmod.stats_models(df).{"Your model name here"}_model(target='corrected_demand', combo = combo, length=length_) for combo in combos")
    

    You might have to do some processing to your model values obtained through the original df or change the values in those df to match the function name. (Eg: df value is "autoarima" but your function name is "arima_model", so giving this value to the exec function will "autoarima_model")