首页 > 解决方案 > 过滤表示状态的 Numpy 数组

问题描述

关于过滤 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, 5)],
      dtype=[('ts', '<i8'), ('data', '<i8')])
>>> x[(x['ts'] > 2) & (x['ts'] < 4.9)]
array([], dtype=[('ts', '<i8'), ('data', '<i8')])
>>>

这正是我所期望的。但是,我还需要包含过滤后的数组5。有没有一种方法可以过滤它,而不是使用 aforwhile循环遍历数组的行并包括在匹配条件的最后一行之后具有索引的行?

标签: pythonnumpy

解决方案


对于这种“正向后视”匹配问题,找不到内置的 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]

为了防止IndexError万一idx_lidx_r为空:

idx = np.concatenate([idx_l[:], idx_r[1:]], axis=0)
np.delete(x, idx)

当过滤条件不返回任何可以从中获取偏移量(包括边界值)的索引时,这种方法可以解决问题。但是它会运行得更慢,因为np.where它被调用了两次。


推荐阅读