Array of values ​​array in numpy array

Here is a little code illustrating 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,0]]) # location of values in A # if I just had 1d values I could use numpy.in1d here indices = array([0, 1]) # example of operation type I need (recalculating f_of_A as needed is not an option) f_of_A[ indices ] 

So basically, I think I need some kind of in1d equivalent for higher dimensions. Is there such a thing? Or is there some other approach?

It looks like there is also a searchsorted () function, but this also works for the 1st array. In this example, I used 2d points, but any solution should work for three points as well.

+3
source share
2 answers

Well, that’s what I came up with.

To find the value of a single multidimensional index, say ii = np.array([1,2]) , we can do:

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

Let it break, we have A == ii , which will give elementary comparisons with ii for each row of A We want the whole line to be true, so we add .all(axis=1) to collapse them. To find where these indexes occur, we connect it to np.where and get the first value of the tuple.

Now I have no quick way to do this with multiple indexes (although I have a feeling that there is one). However, this will do its job:

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

It simply calls above, for each value, values and combines the result.

Update:

Here is for the multidimensional case (all in one move, should be pretty fast):

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

You can use np.in1d in the representation of the source array with all collimated codes in a single dtype variable np.void :

 import numpy as np A = np.array([[1,2], [1,0], [5,3]]) values = np.array([[1,2], [1,0]]) # Make sure both arrays are contiguous and have common dtype common_dtype = np.common_type(A, values) a = np.ascontiguousarray(A, dtype=common_dtype) vals = np.ascontiguousarray(values, dtype=common_dtype) a_view = A.view((np.void, A.dtype.itemsize*A.shape[1])).ravel() values_view = values.view((np.void, values.dtype.itemsize*values.shape[1])).ravel() 

Now each a_view and values_view element is all the coordinates for one point, packed together, so you can do whatever 1D magic you use. I don’t see how to use np.in1d to search for indexes, so I would go the np.searchsorted route:

 sort_idx = np.argsort(a_view) locations = np.searchsorted(a_view, values_view, sorter=sort_idx) locations = sort_idx[locations] >>> locations array([0, 1], dtype=int64) 
+1
source

Source: https://habr.com/ru/post/1493740/


All Articles