在一个熊猫系列中,如果一个值增加5倍,则应该遍历该序列并停止。通过一个简单的示例,到目前为止,它可以正常工作:
list2 = pd.Series([2,3,3,4,5,1,4,6,7,8,9,10,2,3,2,3,2,3,4])
def cut(x):
y = iter(x)
for i in y:
if x[i] < x[i+1] < x[i+2] < x[i+3] < x[i+4] < x[i+5]:
return x[i]
break
out = cut(list2)
index = list2[list2 == out].index[0]
所以我得到正确的输出1和索引5。
但是,如果我使用第二个具有系列类型的列表,而不是(19,)具有(23999,)值,则会出现错误:
pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 3489660928
答案 0 :(得分:2)
您可以执行以下操作:
# compare list2 with the previous values
s = list2.gt(list2.shift())
# looking at last 5 values
s = s.rolling(5).sum()
# select those equal 5
list2[s.eq(5)]
输出:
10 9
11 10
dtype: int64
它发生的第一个索引是
s.eq(5).idxmax()
# output 10
此外,您可以将它们链接在一起:
(list2.gt(list2.shift())
.rolling(5).sum()
.eq(5).idxmax()
)