如何适当地迭代时间序列的数据帧

2024-05-26 00:33:32 发布

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

所以我知道你从来都不想迭代熊猫数据帧,但我找不到解决这个问题的其他方法

我有一系列不同的时间序列,比如说它们是一天结束时的股价。它们位于这样的数据帧中:

   Ticker Price
0   AAA    10
1   AAA    11
2   AAA    10.5
3   BBB    100
4   BBB    110
5   CCC    60
etc.

对于每个股票代码,我想采用各种模型,并对它们进行连续更大批量的数据培训。具体来说,我想建立一个模型,根据第1天的数据进行训练,预测第2天。在第1天和第2天训练同一个模型,预测第3天,等等。对于每一天,我想切片到前一天,并预测该子集[day0:dayN-1]

本质上,我正在实现sklearn的TimeSeriesSplit,除了我自己做之外,因为我正在训练的模型不在sklearn中(例如,一个模型是Prophet

我的想法是在一堆不同的股票上尝试一堆模型,然后我看到哪些模型适合于哪些股票

因此,我在所有数据上运行一个模型的基本代码如下所示:

import pandas as pd


def make_predictions(df):

    res = pd.DataFrame()

    for ticker in df.ticker.unique():
        df_ticker = df[df['ticker'] == ticker]

        for i,_ in df_ticker.iterrows():
            X = df_ticker[0:i]
            X = do_preparations(X)           # do some processing to prepare the data
            m = train_model(X)               # train the model
            forecast = make_predictions(m)   # predict one week

            df_ticker.loc[i,'preds'] = forecast['y'][0]

        res = pd.concat([res,df_ticker])

    return res

但我的代码运行速度非常慢。我能加快速度吗? 我不知道如何使用.apply()或任何其他常见的反迭代技术


Tags: 数据in模型dfformakeressklearn
1条回答
网友
1楼 · 发布于 2024-05-26 00:33:32

考虑几个项目:

  • 首先,通过在循环内调用pd.concat来避免quadratic copying。相反,构建一个数据帧列表/目录,在循环外部连接一次
  • 其次,避免使用DataFrame.iterrows,因为您只使用i。相反,遍历index
  • 第三,对于紧凑性,避免unique()和后续子集[...]。相反,在字典或列表理解中使用groupby(),这可能比list.append方法稍微快一点,并且由于需要多个步骤,因此需要一个内部定义的函数

内部循环可能是不可避免的,因为您实际上运行的是不同的模型

def make_predictions(df):

   def proc_model(sub_df):

      for i in sub_df.index:
         X = sub_df.loc[0:i]
         X = do_preparations(X)           # do some processing to prepare the data
         m = train_model(X)               # train the model
         forecast = make_predictions(m)   # predict one week

         sub_df.loc[i,'preds'] = forecast['y'][0]

      return sub_df   

   # BUILD DICTIONARY OF DATA FRAMES
   df_dict = {i:proc_model(g) for i, g in df.groupby('ticker')}

   # CONCATENATE DATA FRAMES
   res = pd.concat(df_dict, ignore_index=True)

   return res

相关问题 更多 >