【问题标题】:Comparing previous value and next value in Pandas Series比较 Pandas 系列中的前一个值和下一个值
【发布时间】:2019-02-22 06:52:10
【问题描述】:

我有一个带有 OHCL 数据的 pandas 数据框, 我想将 Low 系列中的每个值与该系列中的前一个值和下一个值进行比较。

2018-08-31    1.15839
2018-08-30    1.16411
2018-08-29    1.16511
2018-08-28    1.16618
2018-08-27    1.15938
2018-08-24    1.15340

如果该值小于该系列中的前一个值且小于该系列中的下一个值,我想将该索引中的 新系列 (df.Low) 中的值返回为 True , 否则为 False。

另一种可能性是检索条件为真但附加索引的值。

我尝试使用 zip 并且这有效,但这样做我丢失了索引。

Lows = []
Highs = []

for x,y,z in zip(df.Low_Price[::],df.Low_Price[1::],df.Low_Price[2::]):
    if x > y < z:
        Low = np.around(y, decimals=5)
        Lows.append(Low)

for x,y,z in zip(df.High_Price[::],df.High_Price[1::],df.High_Price[2::]):
    if x < y > z:
        High = np.around(y, decimals=5)
        Highs.append(High)

谢谢!

【问题讨论】:

  • 顺便说一句,您正在引入前瞻偏差(除非“下一个值”是向后看的,即 T-2?)。另外,您的预期输出是什么?
  • 我正在尝试检索所有可能的低点和高点,这是曲折指标的第一步。确定新低的下一步将是如果下一个上涨触及 38.2 斐波那契回撤位并且价格没有越过之前的低点。此步骤是寻找可能的高点和低点候选者,其中前一个和下一个蜡烛不高于(对于高点)和较低(对于低点)。

标签: python pandas loops zip series


【解决方案1】:

使用移位:

对于低,

df[(df['a'].lt(df['a'].shift(-1))) & df['a'].lt(df['a'].shift(1))]

对于高,

df[(df['a'].gt(df['a'].shift(-1))) & df['a'].gt(df['a'].shift(1))]

【讨论】:

    【解决方案2】:

    使用 zip 对您的解决方案稍作修改

    Lows = []
    Highs = []
    
    for i,x,y,z in zip(df.index[1::], df.Low_Price[::],df.Low_Price[1::],df.Low_Price[2::]):
        if x > y < z:
            Low = np.around(y, decimals=5)
            Lows.append([i, Low])
    
    for i,x,y,z in zip(df.index[1::],df.High_Price[::],df.High_Price[1::],df.High_Price[2::]):
        if x < y > z:
            High = np.around(y, decimals=5)
            Highs.append([i, High])
    

    【讨论】:

      【解决方案3】:

      您可以尝试将数据帧值转移到下一个和上一个以检查条件

      考虑的数据框

              0        1
      0   2018-08-31  1.15839
      1   2018-08-30  1.16411
      2   2018-08-29  1.16511
      3   2018-08-28  1.16618
      4   2018-08-27  1.15938
      5   2018-08-24  1.15340
      
      
      [(df[1].ge(df[1].shift())) & df[1].le(df[1].shift(-1))]
      

      输出:

      [0    False
       1     True
       2     True
       3    False
       4    False
       5    False
       Name: 1, dtype: bool]
      

      如果您的意图只是检查整列的低值,您可以使用

      df[1].min()
      

      输出:

      1.1534
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多