使用Numpy查找给定数组多个值的索引 [英] Find index given multiple values of array with Numpy

查看:354
本文介绍了使用Numpy查找给定数组多个值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解Numpy可以使用 numpy.where 给定我们想要的值来生成数组的索引。我的问题:是否有一个可以生成索引给定多个值的函数。

I understand that Numpy can generate index of an array given the value that we are looking for with numpy.where. My question: Is there a function that can generate index given multiple values.

例如,使用此数组

a = np.array([1.,0.,0.,0.,1.,1.,0.,0.,0.,0.,...,1.,1.])

如果我可以只指定4个零,函数可以告诉它的索引,然后我可以立即用另一个值替换它们。我有一个可以识别模式的功能,但是效率不高。任何指针都会非常有帮助。

It will be great if I can just specify 4 zeros and the function can tell the index of it then I can replace those right away with another value. I have a function that can recognize the pattern but it is not efficient. Any pointers will be very helpful

推荐答案

似乎我每周大约给出一次此答案。最快,内存效率最高的方法是在 as_strided 视图上使用 void 视图

Seems like I give this answer once a week or so. Fastest and most memory-efficient way is to use void views over as_strided views

def rolling_window(a, window):  #based on @senderle's answer: https://stackoverflow.com/q/7100242/2901002
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    c = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
    return c

def vview(a):  #based on @jaime's answer: https://stackoverflow.com/a/16973510/4427777
    return np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))

def pattwhere_void(pattern, a): # Using @PaulPanzer's template form above
    k, n = map(len, (pattern, a))
    pattern = np.atleast_2d(pattern)
    a = np.asanyarray(a)
    if k>n:
        return np.empty([0], int)
    return np.flatnonzero(np.in1d(vview(rolling_window(a, k)), vview(pattern)))

这篇关于使用Numpy查找给定数组多个值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆