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, 5)],
dtype=[('ts', '<i8'), ('data', '<i8')])
>>> x[(x['ts'] > 2) & (x['ts'] < 4.9)]
array([], dtype=[('ts', '<i8'), ('data', '<i8')])
>>>
这正是我所期望的。但是,我还需要包含过滤后的数组5
。有没有一种方法可以过滤它,而不是使用 afor
或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]
为了防止IndexError
万一idx_l
或idx_r
为空:
idx = np.concatenate([idx_l[:], idx_r[1:]], axis=0)
np.delete(x, idx)
当过滤条件不返回任何可以从中获取偏移量(包括边界值)的索引时,这种方法可以解决问题。但是它会运行得更慢,因为np.where
它被调用了两次。
推荐阅读
- javascript - 无法列出通过推送发送的数据
- spring - Spring Cloud Stream 迁移
- web-services - 通过网络服务更新 Prestashop 数量
- amazon-s3 - AWS Lambda 缺少从 S3 到 SQS 的事件
- azure-cosmosdb - 无服务器帐户不支持在容器上设置报价吞吐量或自动驾驶仪。Azure Cosmos DB 迁移工具
- javascript - 防止 TypeError:更新 [0] 在 Vue.js/Django 应用程序中未定义
- javascript - 我如何在这个函数之外使用数量变量请任何人帮助我
- angular - 将方向断点添加到默认的 Angular Flex-Layout 断点
- java - 如何在 Spring 中等待 WebClient 超时响应?
- javascript - XHR 获取响应 javascript 未执行