Python 使用超过特定阈值的累积和迭代数据

Python 使用超过特定阈值的累积和迭代数据,python,iteration,Python,Iteration,假设我有一列X和它的索引I,如下所示: 索引X 0 0.007934 1 0.015535 2 0.000368 3 0.000212 4 0.000111 5 -0.001123 6 -0.000539 7 -0.000142 8 -0.000114 9 -0.002034 10 -0.041414 ... 我想对其进行迭代以创建一个新的列Y,该列满足: -如果指数i是X_i累计总和超过阈值0.0006的第一个退出指数

假设我有一列X和它的索引I,如下所示:

索引X
0     0.007934
1     0.015535
2     0.000368
3     0.000212
4     0.000111
5    -0.001123
6    -0.000539
7    -0.000142
8    -0.000114
9    -0.002034
10   -0.041414
...
我想对其进行迭代以创建一个新的列Y,该列满足: -如果指数i是X_i累计总和超过阈值0.0006的第一个退出指数,则指数i处的Y值将记录为$Y_i='是' -否则记录为$Y_i='否'

以下是前7个索引的图示:

abs(cumulative sum(X[:0]) = 0.007934 > 0.0006 then Y_0 = Yes.

abs(cumulative sum(X[1:1]) = 0.015535 > 0.0006 then Y_1 = Yes

abs(cumulative sum(X[2:2]) = 0.000368 < 0.0006 then Y_2 = No

abs(cumulative sum(X[2:3]) = 0.000580 < 0.0006 then Y_3 = No

abs(cumulative sum(X[2:4]) = 0.000691 > 0.0006 then Y_4 = Yes

abs(cumulative sum(X[5:5]) = 0.001123 > 0.0006 then Y_5 = Yes.

abs(cumulative sum(X[6:6]) = 0.000539 < 0.0006 then Y_6 = No

abs(cumulative sum(X[6:7]) = 0.000681 > 0.0006 then Y_7 = Yes
abs(累计和(X[:0])=0.007934>0.0006,则Y_0=Yes。
abs(累计和(X[1:1])=0.015535>0.0006,则Y_1=Yes
abs(累计和(X[2:2])=0.000368<0.0006,则Y_2=No
abs(累积和(X[2:3])=0.000580<0.0006,则Y_3=No
abs(累积和(X[2:4])=0.000691>0.0006,则Y_4=Yes
abs(累积和(X[5:5])=0.001123>0.0006,则Y_5=Yes。
abs(累积和(X[6:6])=0.000539<0.0006,则Y_6=No
abs(累积和(X[6:7])=0.000681>0.0006,则Y_7=Yes

迭代直到样本耗尽

你能帮我解决这个问题吗?非常感谢。

更新我已经根据你的评论更正了代码。如果我理解正确,那么解决你问题的代码可能如下所示:

def Y(x, x_history):
    x_history.append(abs(x))
    if sum(x_history) > 0.0006:
        return True, []
    return False, x_history

X = [0.007934, 0.015535, 0.000368, 0.000212, 0.000111, -0.001123, -0.000539,
     -0.000142, -0.000114, -0.002034, -0.041414, 0.002792, 0.016099, 0.006480,
     -0.007141, -0.010191, -0.044790, -0.004887, -0.009217, -0.039200,
     -0.066433, 0.021649, 0.004331, -0.000393, -0.005410, 0.006222, 0.001342,
     0.065700, 0.003055, -0.004560]

print('index   X    Y')
x_history = []
for i, x in enumerate(X):
    y, x_history = Y(x, x_history)
    print(i, x, 'Yes' if y else 'No')
输出为:

index   X    Y
0 0.007934 Yes
1 0.015535 Yes
2 0.000368 No
3 0.000212 No
4 0.000111 Yes
5 -0.001123 Yes
6 -0.000539 No
7 -0.000142 Yes
8 -0.000114 No
9 -0.002034 Yes
10 -0.041414 Yes
11 0.002792 Yes
12 0.016099 Yes
13 0.00648 Yes
14 -0.007141 Yes
15 -0.010191 Yes
16 -0.04479 Yes
17 -0.004887 Yes
18 -0.009217 Yes
19 -0.0392 Yes
20 -0.066433 Yes
21 0.021649 Yes
22 0.004331 Yes
23 -0.000393 No
24 -0.00541 Yes
25 0.006222 Yes
26 0.001342 Yes
27 0.0657 Yes
28 0.003055 Yes
29 -0.00456 Yes

很抱歉,我没有解释清楚,您误解了我的问题。我刚刚编辑了问题。我需要计算X_I的累积和,然后将此累积和与阈值(0.0006)进行比较。如果累积和(X_I)>0.0006,则返回值为“是”和“否”否则。这些返回值将保存在一个数组Y中,其索引为i。如果我们得到的返回值为“否”,则下一个累积和(X_(i+1))=cumsum(X_i)+X_(i+1)。你仍然误解了我的问题。没有很好地解释问题是我的错。我只是重新编辑了问题。我想与阈值比较的值是X的累积和,而不是绝对值的和。请更新你的示例,因为它包括X值,而不是累积X值。无论如何,我认为我的解决方案所需的修改是微不足道的。