过滤表示状态的Numpy数组

问题描述 投票:0回答:1

关于过滤numpy数组有很多问题,包括:

Filter rows of a numpy array?

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

>>> 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。除了forwhile循环以外,是否还有其他方法可以对它进行过滤,因此可以对数组的行进行迭代,并在符合条件的最后一行之后包含具有索引的行?

python numpy
1个回答
0
投票

找不到针对此类“正向后看”匹配问题的内置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]

为了防止在IndexErroridx_l为空的情况下出现idx_r

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

此方法解决了以下问题:当过滤条件未返回可从中获取偏移量(包括边界值)的任何索引时。但是,由于两次调用np.where,它的运行速度会变慢。

© www.soinside.com 2019 - 2024. All rights reserved.