Python 过滤表示状态的Numpy数组

Python 过滤表示状态的Numpy数组,python,numpy,Python,Numpy,关于numpy阵列的筛选,存在各种问题,包括: 但我有一个稍微不同的问题: >>> x = np.empty(shape=(5,), dtype=[('ts', 'i8'), ('data', 'i8')]) >>> x['ts'] = [0, 1, 2, 5, 6] >>> x['data'] = [1, 2, 3, 4, 5] >>> x array([(0, 1), (1, 2), (2, 3), (5, 4), (6

关于numpy阵列的筛选,存在各种问题,包括:

但我有一个稍微不同的问题:

>>> x = np.empty(shape=(5,), dtype=[('ts', 'i8'), ('data', 'i8')])
>>> x['ts'] = [0, 1, 2, 5, 6]
>>> x['data'] = [1, 2, 3, 4, 5]
>>> x
array([(0, 1), (1, 2), (2, 3), (5, 4), (6, 5)],
      dtype=[('ts', '<i8'), ('data', '<i8')])
>>> x[(x['ts'] > 2) & (x['ts'] < 4.9)]
array([], dtype=[('ts', '<i8'), ('data', '<i8')])
>>>

这正是我所期望的。但是,我需要过滤的数组也包含5。有没有其他方法可以过滤它,然后使用for或while循环迭代数组中的行,并包括索引位于匹配条件的最后一行之后的行?

找不到这种“正向查找”匹配问题的内置numpy解决方案。也许这样做可以:

idx_l = np.where(x['ts']<=2)[0]
idx_r = np.where(x['ts']>=4.9)[0]
x[idx_l[-1]+1:idx_r[0]+1]

这种方法解决了当过滤条件不返回任何索引时的问题,您可以从该索引中获取偏移量以包含边界值。但是,由于np.where被调用了两次,它的运行速度会变慢。

当您说还需要包含5时,您的意思是什么?@dumbPy我需要根据ts进行筛选,其中结束条件小于5,但我需要包含ts==5的行。好的旧2&x['ts'有什么不对@dumbPy Nothing如果你知道5是下一个ts,我就不知道5是下一个ts。我只知道最小值和最大值
idx = np.concatenate([idx_l[:], idx_r[1:]], axis=0)
np.delete(x, idx)