0

我已经为 SPC 编写了代码,并且试图突出显示某些失控的运行。所以我想知道是否有一种方法可以在数组中提取 n(在我的情况下为 7)数量增加的元素,以便在绘制它们时可以使用红色进行索引。这是我尝试过的,但我显然得到了一个索引错误。

import  numpy as np
import matplotlib.pyplot as plt

y = np.linspace(0,10,15) 
x = np.array([1,2,3,4,5,6,7,8,9,1,4,6,4,6,8])
col =[]
  
for i in range(len(x)):
    if x[i]<x[i+1] and x[i+1]<x[i+2] and x[i+2]<x[i+3] and x[i+3]<x[i+4] and x[i+4]<x[i+5] and x[i+5]<x[i+6] and x[i+6]<x[i+7]:
        col.append('red')  
    elif x[i]>x[i+1] and x[i+1]>x[i+2] and x[i+2]>x[i+3] and x[i+3]>x[i+4] and x[i+4]>x[i+5] and x[i+5]>x[i+6] and x[i+6]>x[i+7]:
        col.append('red')  
    else:
        col.append('blue') 
  
for i in range(len(x)):
      
    # plotting the corresponding x with y 
    # and respective color
    plt.scatter(y[i], x[i], c = col[i], s = 10,
                linewidth = 0)

任何帮助将不胜感激!

4

2 回答 2

0

要确定列表的所有整数元素是否都在升序,您可以这样做:-

def ascending(arr):
    _rv = True
    for i in range(len(arr) - 1):
        if arr[i + 1] <= arr[i]:
            _rv = False
            break
    return _rv


a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 10, 11, 12, 13, 14, 16]
a2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16]

print(ascending(a1))
print(ascending(a2))

如果你想限制升序值的顺序,那么你可以只使用嵌套循环。它可能看起来不优雅,但它比将数据帧混合起来非常高效且简单得多:-

def ascending(arr, seq):
    for i in range(len(arr) - seq + 1):
        state = True
        for j in range(i, i + seq - 1):
            if arr[j] >= arr[j + 1]:
                state = False
                break
        if state:
            return True
    return False


a1 = [100, 99, 98, 6, 7, 8, 10, 11, 12, 13, 14, 13]
a2 = [9, 8, 7, 6, 5, 4, 3, 2, 1]

print(ascending(a1, 7))
print(ascending(a2, 7))
于 2021-08-05T19:53:32.000 回答
0

正如安迪在他的评论中所说,你会得到索引错误,因为i=8你会得到 15,这是 x 的长度。

要么你只循环 len(x)-7 并重复 col 7 中的最后一个条目,要么你可以做这样的事情:

import  numpy as np
import matplotlib.pyplot as plt

y = np.linspace(0,10,20)
x = np.array([1,2,3,4,5,6,1,2,3,1,0,-1,-2,-3,-4,-5,-6,4,5])
col =[]

diff = np.diff(x) # get diff to see if x inc + or dec - // len(x)-1
diff_sign = np.diff(np.sign(diff)) # get difference of the signs to get either 1 (true) or 0 (false) // len(x)-2
zero_crossings = np.where(diff_sign)[0] + 2 # get indices (-2 from len(x)-2) where a zero crossing occures
diff_zero_crossings = np.diff(np.concatenate([[0],zero_crossings,[len(x)]])) # get how long the periods are till next zero crossing

for i in diff_zero_crossings:
    if i >= 6:
        for _ in range(i):
            col.append("r")
    else:
        for _ in range(i):
            col.append("b")

for i in range(len(x)):

    # plotting the corresponding x with y
    # and respective color
    plt.scatter(y[i], x[i], c = col[i], s = 10,
            linewidth = 0)

plt.show()
于 2021-08-05T19:55:53.623 回答