Numpy 在向量中截取在一定取值范围内的元素
在使用Numpy设计算法,或者进行信号处理时,经常会涉及给定取值范围,截取该取值范围内的数据。例如,box plot 统计中,给定下四分位点 Q 1 Q_1 Q1与上四分位点 Q 3 Q_3 Q3,求 [ Q 1 , Q 3 ] [Q_1,Q_3] [Q1,Q3]内的样本;给定信号的时间戳,需要截取某个时间范围的信号。
1、给定上界或下界
当给定了数据的上界或下界时,情况比较简单
a = np.array([1,2,3,4,5,6])
index = np.argwhere(1< a)
new_a = a[index]
2、同时给定上界或下界
当同时给定上界 t h 1 th_1 th1和下界 t h 2 th_2 th2时,可以使用如下语句
th1, th2 = 2, 4
a = np.array([1,2,3,4,5,6])
index = np.argwhere(a > th1)
new_a = a[index]
index = np.argwhere(a < th2)
new_a = new_a[index]
但是当需要保留向量中各元素在向量中的原始索引时,就无法使用上述方法,如给定信号的时间戳,需要截取某个时间范围的信号。
# sig 是array类型的时间序列信号, sig_timestamp是其时间戳
th1, th2 = 1618504534.1906, 1618505534.1906
index1 = set(np.argwhere(sig_timestamp >= th1).flatten().tolist())
index2 = set(np.argwhere(sig_timestamp <= th2).flatten().tolist())
index = list(set.intersection(index1, index2))
sig_seg = sig[index]