Numpy: For every element in one array, find the index in another array

后端 未结 8 1091
旧巷少年郎
旧巷少年郎 2020-12-02 18:36

I have two 1D arrays, x & y, one smaller than the other. I\'m trying to find the index of every element of y in x.

I\'ve found two naive ways to do this, the fir

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 18:46

    The numpy_indexed package (disclaimer: I am its author) contains a function that does exactly this:

    import numpy_indexed as npi
    indices = npi.indices(x, y, missing='mask')
    

    It will currently raise a KeyError if not all elements in y are present in x; but perhaps I should add a kwarg so that one can elect to mark such items with a -1 or something.

    It should have the same efficiency as the currently accepted answer, since the implementation is along similar lines. numpy_indexed is however more flexible, and also allows to search for indices of rows of multidimensional arrays, for instance.

    EDIT: ive changed the handling of missing values; the 'missing' kwarg can now be set with 'raise', 'ignore' or 'mask'. In the latter case you get a masked array of the same length of y, on which you can call .compressed() to get the valid indices. Note that there is also npi.contains(x, y) if this is all you need to know.

提交回复
热议问题