首页 > 解决方案 > 从过滤的系列创建一个序列行

问题描述

我正在尝试创建一个包含从 t0 到 t(n) 的列的行。我有一个完整的数据框 (df) 来存储完整的数据集,以及一个我感兴趣的数据系列 (df_t) 特定的时间标记。我想要创建一个时间标记为 t0 的行,然后是前一个来自完整数据帧的 [sequence_length] 行。

def t_data(df, df_t, col_names, sequence_length):
  df_ret = pd.DataFrame()

  for i in range(sequence_length):
    col_names_seq = [col_name + "_" + str(i) for col_name in col_names]
    df_ret[col_names_seq] = df[df.shift(i)["time"].isin(df_t)][col_names]

  return df_ret

跑步:

t_data(df, df_t, ["close"], 3)

我得到:

        close_0 close_1 close_2
1110    1.32080 NaN NaN
2316    1.30490 NaN NaN
2549    1.30290 NaN NaN

明显的问题是:

df[df.shift(i)["time"].isin(df_t)][col_names]

我尝试了几种方法,但似乎无法选择围绕子集的数据。

样品(df):

    time    open    close   high    low volume  EMA21   EMA13   EMA9
20  2005-01-10 04:10:00 1.3071  1.3074  1.3075  1.3070  32.0    1.306624    1.306790    1.306887
21  2005-01-10 04:15:00 1.3074  1.3073  1.3075  1.3073  16.0    1.306685    1.306863    1.306969
22  2005-01-10 04:20:00 1.3073  1.3072  1.3074  1.3072  35.0    1.306732    1.306911    1.307015

样本(df_t):

1110   2005-01-13 23:00:00
2316   2005-01-18 03:30:00
2549   2005-01-18 22:55:00
Name: time, dtype: datetime64[ns]

我没有数据,但希望这张图有帮助: 在此处输入图像描述

标签: pandasdata-wrangling

解决方案


def t_data(df, df_T, n):
    # Get the indexs of the original df that matches with the values of df_T
    indexs = df.reset_index().merge(df_T, how="inner")['index'].tolist()

    #create new index list where we will store the index-n vales
    newIndex = []

    #create list of values to subtract from index
    toSub = np.arange(n)

    #loop over index values and subtract the values, and append in newIndex
    for i in indexs:
        for sub in toSub:
            v = i - sub
            newIndex.append(v)

    #Use iloc to get all the rows in the original df with the newIndex values that we want
    closedCosts = df.iloc[newIndex].reset_index(drop = True)["close"].values

    #concat our data back to df_T, and reshape closedCosts by n columns
    df_final = pd.concat([df_T, pd.DataFrame(closedCosts.reshape(-1, n))], axis= 1)

    #return final df
    return df_final

这应该可以满足您的要求。最简单的方法是从原始 df 中找出您想要的所有索引及其相应的结束值。注意:您必须在此之后重命名列,但所有值都在那里。


推荐阅读