我有一个1d numpy字符串数组(dtype='U')
,名为ops
,长度为15MM,其中我需要找到所有索引,其中我找到了一个名为op
83000次的字符串
到目前为止,numpy赢得了比赛,但仍然需要3个小时:indices = np.where(ops==op)
我也尝试了np.unravel_index(np.where(ops.ravel()==op), ops.shape)[0][0]
,没有太大区别
我正在尝试一种cython方法,其随机数据与原始数据类似,但其速度比numpys解决方案慢40倍左右。这是我的第一个cython代码也许我可以改进它。 Cython代码:
import numpy as np
cimport numpy as np
def get_ixs(np.ndarray data, str x, np.ndarray[int,mode="c",ndim=1] xind):
cdef int count, n, i
count = 0
n = data.shape[0]
i = 0
while i < n:
if (data[i] == x):
xind[count] = i
count += 1
i += 1
return xind[0:count]
如果您使用相同的
data
多次调用get_ixs
,最快的解决方案是将data
预处理为dict
,然后在查询字符串时获得O(1)查找(恒定时间)。dict的键是字符串
x
,该键的值是包含满足data[i] == x
的索引的列表。代码如下:
输出:
如果使用相同的
dict_str_to_indices
多次调用get_ixs
,则这是最佳渐近解(O(1)查找)相关问题 更多 >
编程相关推荐