如何根据pandas列值调用python函数?

问题描述 投票:0回答:2

我有一个

pandas dataframe
,其中列出了物品、它们的销售地点,以及在所有模型中为所述物品提供最低映射的模型。

这是这个 df 的示例。

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)

我想使用

model
的值来调用存储在类中的模型函数并运行返回数据帧的函数。

例如,如果模型是“TES”,那么我希望运行以下代码行:

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

如果模型是

autoarima
那么将运行以下内容

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

如果有帮助,以下内容将始终相同:

df = [statmod.stats_models(df).
以及
(target='corrected_demand', combo = combo, length=length_) for combo in combos]
。只有模型函数本身所在的中间位置会发生变化。

我从未做过这种类型的动态编码,其中数据帧值调用一行代码来运行。这可能吗?

python pandas oop dynamic-programming
2个回答
0
投票

您可以使用 pandas 中的 apply 方法根据特定列中的值调用 Python 函数。 在此示例中,使用 apply 方法将 custom_function 应用于“年龄”列。结果存储在名为“Age_Status”的新列中。 custom_function 检查年龄是否小于 30 岁,如果为 true,则返回“Young”,否则返回“Not Young”。

您可以将 custom_function 替换为您自己的函数,并根据您感兴趣的列中的值调整逻辑。这种方法很灵活,允许您使用任何自定义函数来处理 DataFrame 列。


0
投票
import pandas as pd


data = {'column_name': ['function1', 'function2', 'function1', 'function2']}
df = pd.DataFrame(data)


def function1():
    print("Calling Function 1")

def function2():
    print("Calling Function 2")


function_mapping = {
    'function1': function1,
    'function2': function2,
}


df['result'] = df['column_name'].apply(lambda x: function_mapping[x]())

输出结果:

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.