python - 排序数组的 np.where 的更快替代方案
问题描述
给定一个沿每一行排序的大数组a
,是否有比 numpy 更快的替代方法np.where
来找到索引在哪里min_v <= a <= max_v
?我想利用数组的排序特性应该能够加快速度。
np.where
这是用于在大型数组中查找给定索引的设置示例。
import numpy as np
# Initialise an example of an array in which to search
r, c = int(1e2), int(1e6)
a = np.arange(r*c).reshape(r, c)
# Set up search limits
min_v = (r*c/2)-10
max_v = (r*c/2)+10
# Find indices of occurrences
idx = np.where(((a >= min_v) & (a <= max_v)))
解决方案
您可以使用np.searchsorted
:
import numpy as np
r, c = 10, 100
a = np.arange(r*c).reshape(r, c)
min_v = ((r * c) // 2) - 10
max_v = ((r * c) // 2) + 10
# Old method
idx = np.where(((a >= min_v) & (a <= max_v)))
# With searchsorted
i1 = np.searchsorted(a.ravel(), min_v, 'left')
i2 = np.searchsorted(a.ravel(), max_v, 'right')
idx2 = np.unravel_index(np.arange(i1, i2), a.shape)
print((idx[0] == idx2[0]).all() and (idx[1] == idx2[1]).all())
# True
推荐阅读
- php - 尝试突出显示php中的某些单词时出现代码执行错误
- rust - Rust 中的迭代器类型
- amazon-web-services - 使用 url 访问 AWS 存储桶
- build-automation - 将新项目添加到 SharePoint 列表时,向匹配项目类别的用户发送电子邮件通知
- sql - 在当前行中,对代表上周(7 天)记录的行的数据求和
- bash - 创建一个运行带有用户定义参数的 sql 脚本的 sh 脚本
- python-3.x - 如何在类方法中使用 Python @click 命令装饰器?
- java - 排序时Java lambda抛出NPE
- python - 如何使用逻辑回归训练高度不平衡的数据进行链接预测
- c# - 为什么我得到 NullReferenceException,如果有空检查