Python如何通过for循环提高子集元组键字典的性能?

2024-05-13 20:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两本带元组键的字典。我将每一个字典分成3个小字典,然后将预测模型应用到每一个字典。见下文

# Subset dictionaries from df_dict140 and df_dict150
# df_dict140 has 456 rows and df_dict150 has 415
# I subsetted the them by 200
dic1 = {k: df_dic[k] for k in df_dict140[:200]}
dic2 = {k: df_dic[k] for k in df_dict140[200:400]}
dic3 = {k: df_dic[k] for k in df_dict140[400:456]}

dic4 = {k: df_dic[k] for k in df_dict150[:200]}
dic5 = {k: df_dic[k] for k in df_dict150[200:400]}
dic6 = {k: df_dic[k] for k in df_dict150[400:415]}

把模型应用到每一本字典上

def predictionModel(pred_dict): 
    prediction = {}
    for (key1, key2), value in pred_dict.items():
        m = Prophet().fit(value)
        future = m.make_future_dataframe(periods = 365)
        forecast = m.predict(future)
        prediction[key2] = forecast[['ds','yhat']].tail()    
    return prediction 

预测结果

prediction1 = predictionModel(dic1)
prediction2 = predictionModel(dic2)
prediction3 = predictionModel(dic3)
prediction4 = predictionModel(dic4)
prediction5 = predictionModel(dic5)
prediction6 = predictionModel(dic6)

是否可以编写一个函数或for循环来完成上述工作,这样就不需要对字典进行两次子集,只需一次就可以得到结果。你知道吗


Tags: andin模型dffor字典futurehas
2条回答

我仍然不明白你在用Prophet做什么,但是如果你只是想用编程的方式来切分字典:

for i in range(0,max(len(dict140),len(dict150)),200):
    d140_slice = {k: df_dic[k] for k in dict140[i:i+200]}
    d150_slice = {k: df_dic[k] for k in dict150[i:i+200]}
    #do something with the slices.
# Note that Python will let you index beyond the end of lists without issue
smaller_dicts = [{k: df_dic[k] for k in dfd[200*i:200*(i+1)]}
                 for dfd in [df_dict140, df_dict150]
                 for i in range(3)]

predictions = [predictionModel(sd) for sd in smaller_dicts]

相关问题 更多 >