location of array of values in numpy array

后端 未结 2 1890
春和景丽
春和景丽 2021-01-21 09:48

Here is a small code to illustrate the problem.

A = array([[1,2], [1,0], [5,3]])
f_of_A = f(A)   # this is precomputed and expensive


values = array([[1,2], [1,         


        
2条回答
  •  死守一世寂寞
    2021-01-21 10:12

    Okay, this is what I came up with.

    To find the value of one multi-dimensional index, let's say ii = np.array([1,2]), we can do:

    n.where((A == ii).all(axis=1))[0]
    

    Let's break this down, we have A == ii, which will give element-wise comparisons with ii for each row of A. We want an entire row to be true, so we add .all(axis=1) to collapse them. To find where these indices happen, we plug this into np.where and get the first value of the tuple.

    Now, I don't have a fast way to do this with multiple indices yet (although I have a feeling there is one). However, this will get the job done:

    np.hstack([np.where((A == values[i]).all(axis=1))[0] for i in xrange(len(values))])
    

    This basically just calls the above, for each value of values, and concatenates the result.

    Update:

    Here is for the multi-dimensional case (all in one go, should be fairly fast):

    np.where((np.expand_dims(A, -1) == values.T).all(axis=1).any(axis=1))[0]
    

提交回复
热议问题