熊猫 - 寻找转折点

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

我有一个pandas专栏,我想找到数据中的每个转折点并保存到一个新列。

Index Col A
 1     1
 2     3
 3     5
 4     4
 5     8
 6     1
 7     2
 8     7
 9     5
 10    3

为了找到转折点,我可以使用index -1 > index < index+1来制作

Index Col A  TP
 1     1     0
 2     3     0 
 3     5     1 #turning point
 4     4     1 
 5     8     1
 6     1     1
 7     2     0
 8     7     0
 9     5     0
 10    3     0

但是我认为使用5点计算(index-2 > index -1 > index < index+1 < index+2或反向)来防止这么多误报是更准确的。

Index Col A  TP
 1     1     0
 2     3     0 
 3     5     0
 4     4     0 
 5     8     0
 6     1     0
 7     2     0
 8     7     1
 9     5     0
 10    3     0

如何在有这么多条件的熊猫中做到这一点?一个复杂的np.where?

python pandas
1个回答
3
投票

你必须做一些转变:

df["TP"] = ((df["Col A"].shift(-2) < df["Col A"].shift(-1)) & 
            (df["Col A"].shift(-1) < df["Col A"]) &
            (df["Col A"].shift( 1) < df["Col A"]) &
            (df["Col A"].shift( 2) < df["Col A"].shift( 1))).astype(int)
df["TP"]
#1    0
#2    0
#3    0
#4    0
#5    0
#6    0
#7    1
#8    0
#9    0
© www.soinside.com 2019 - 2024. All rights reserved.