首页 > 解决方案 > 比较 Pandas 系列中的前一个值和下一个值

问题描述

我有一个带有 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)

谢谢!

标签: pythonpandasloopszipseries

解决方案


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

考虑的数据框

        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

推荐阅读