location of array of values in numpy array

后端 未结 2 1861
春和景丽
春和景丽 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 09:58

    You can use np.in1d over a view of your original array with all coordinates collapsed into a single variable of dtype 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 item of a_view and values_view is all coordinates for one point packed together, so you can do whatever 1D magic you would use. I don't see how to use np.in1d to find indices though, 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)
    

提交回复
热议问题