【问题标题】:Filtering Numpy Array representing state过滤表示状态的 Numpy 数组
【发布时间】:2020-05-21 15:33:42
【问题描述】:

关于过滤 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 循环遍历数组的行并在匹配条件的最后一行之后包含索引的行之外,有没有其他方法可以过滤它?

【问题讨论】:

  • 当你说你还需要包含“5”是什么意思?
  • @dumbPy 我需要基于ts 进行过滤,其中结束条件为ts == 5 的行。
  • 好老的&lt;= 5 有什么问题? x[(x['ts'] &gt; 2) &amp; (x['ts'] &lt;= 5)]
  • @dumbPy 如果你知道 5 是下一个 ts,那就什么都没有了。当我必须过滤时,我不知道 5 是下一个ts。我只知道最小值和最大值

标签: python numpy


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-01-31
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2014-11-27
    • 2018-06-01
    相关资源
    最近更新 更多