python如何根据阈值选择数据?

Python如何根据阈值选择数据?

我在下面有一个数组:
a=np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1])
我想要的是在此向量上用阈值选择数据。

问题1:以threshold=8为例,大于等于8的元素保留,小于8为0。
输出向量应该是这样的:
a_output = [0, 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,]

问题2:以threshold=8为例,大于等于8的元素保留,并且向两边扩展保留两个数据,小于8为0。
输出向量应该是这样的:
a_output = [0, 0, 0, 0, 0, 6, 7, 8, 9, 8, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 8, 7, 6, 0, 0, 0, 0, 0,]

(希望能获得解答,不知道我的表述是否清晰)


from hashlib import new
import numpy as np

a=np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1])
threshold=8
a_output=np.copy(a)
a[np.where(a_output<threshold)]=0
print(a_output)
index=np.where(a>=threshold)[0]
new_index=set()
for i in index:
    for j in range(i-2,i+3):
        new_index.add(j)
a_output=np.array([a[i] if i in new_index else 0 for i in range(len(a))])
print(a_output)