如何为时间序列在熊猫数据框上进行适当的迭代

问题描述 投票:1回答:1

所以我知道您从不想要遍历Pandas DataFrame,但是我找不到解决此问题的另一种方法。

我有很多不同的时间序列,说它们是当日股票价格。它们在这样的DataFrame中:

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

对于每个股票行情指示器,我想采用各种模型,并在依次更大的数据批次上对其进行训练。具体来说,我想建立一个模型,对第一天的数据进行训练,预测第二天。在第1天和第2天训练相同的模型,预测第3天,依此类推。对于每一天,我都想分割到前一天并预测该子集[day0:dayN-1]。

基本上,我正在实现sklearn的TimeSeriesSplit,但我自己做,因为我正在训练的模型不在sklearn中(例如,一个模型是Prophet。]

这个想法是我在许多不同的股票交易代码上尝试一堆模型,然后查看哪些模型对哪些股票代码运行良好。

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

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()或其他任何常见的反迭代技术。

python pandas
1个回答
0
投票

考虑几个项目:

  • 首先,通过在循环内调用quadratic copying来避免pd.concat。而是在循环外构建要连接的数据帧的列表/字典。第二,避免使用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

© www.soinside.com 2019 - 2024. All rights reserved.