我正在处理时间序列。我已经使用下面的代码计算了高和低分形。我想做的是,如果有分形标记,请将其保留在每一列中,直到出现新的分形为止。我尝试使用np.where
,但似乎使用错误的方式。这是我的代码:
df['high_fractal'] = np.where((df['High']>df['High'].shift(-1)) & (df['High']>df['High'].shift(-2)) & (df['High']>df['High'].shift(1)) & (df['High']>df['High'].shift(2)) & (df['High'].shift(-2)), 1, 0)
df['low_fractal'] = np.where((df['Low']<df['Low'].shift(-1)) & (df['Low']<df['Low'].shift(-2)) & (df['Low']<df['Low'].shift(1)) & (df['Low']<df['Low'].shift(2)) & (df['Low'].shift(-2)), 1, 0)
df['lf'] = np.zeros((len(df)))
df['hf'] = np.zeros((len(df)))
df['lf'] = np.where(df['low_fractal']==1, df['Low'], df['lf'].shift(1))
df['hf'] = np.where(df['high_fractal']==1, df['High'], df['hf'].shift(1))
print(df[['Date', 'High', 'Low', 'lf', 'hf']].tail())
Date High Low lf hf
10007 2018-08-06 1.1574 1.1527 1.1527 0.0000
10008 2018-08-07 1.1610 1.1547 0.0000 0.0000
10009 2018-08-08 1.1629 1.1571 0.0000 1.1629
10010 2018-08-09 1.1620 1.1525 0.0000 0.0000
10011 2018-08-10 1.1536 1.1388 0.0000 0.0000
列lf和hf应当包含先前的lf和hf而不是零。在这种情况下,所有其他lf值应为1.1527,而hf(在2018-08-08以下)应为1.1629。我该如何实现?
谢谢