0

I am a newbie in numpy. I have an array A of size 6 x 2 of values and an array B of size 4 x 2. I want as result an array C filled with indices i of B.

Here is an example of inputs and outputs:

A = [[ 240.  240.][   0.  480.][   0.  960.][   0.  480.][   0.  720. ][   0.  480.]]
B = [[   0.  480.][   0.  720.][   0.  960.][ 240.  240.]]

C = [3, 0, 2, 0, 1, 0]

I tried with np.searchsorted() but only accept 1d array I didn't find the way how to do this. Please advice me. Thank you.

Roman
  • 13
  • 1
  • The example code is not valid python. Are those `lists`, `np.arrays` or something else? Comparing floats is generally not reliable. – Michael Szczesny May 24 '22 at 19:40
  • When displaying arrays, it is better to show the `repr` version rather than the print/str. The `repr`, or list equivalent (like your `C`), can be copy-n-pasted to our own python session; the `str` version without the commas requires a lot of editing. – hpaulj May 24 '22 at 21:05

1 Answers1

0

Assuming there is necessarily a match, you can use:

np.isclose(abs(B-A[:, None]), 0).all(2).argmax(1)

Output:

array([3, 0, 2, 0, 1, 0])

How it works

This computes element-wise the absolute difference between A and B, then converts to boolean to identify the values close to 0. If all are True we identify the index with argmax as True > False

intermediates

abs(B-A[:, None])

array([[[240., 240.],
        [240., 480.],
        [240., 720.],
        [  0.,   0.]],

       [[  0.,   0.],
        [  0., 240.],
        [  0., 480.],
        [240., 240.]],

       [[  0., 480.],
        [  0., 240.],
        [  0.,   0.],
        [240., 720.]],

       [[  0.,   0.],
        [  0., 240.],
        [  0., 480.],
        [240., 240.]],

       [[  0., 240.],
        [  0.,   0.],
        [  0., 240.],
        [240., 480.]],

       [[  0.,   0.],
        [  0., 240.],
        [  0., 480.],
        [240., 240.]]])

np.isclose(abs(B-A[:, None]), 0)

array([[[False, False],
        [False, False],
        [False, False],
        [ True,  True]],

       [[ True,  True],
        [ True, False],
        [ True, False],
        [False, False]],

       [[ True, False],
        [ True, False],
        [ True,  True],
        [False, False]],

       [[ True,  True],
        [ True, False],
        [ True, False],
        [False, False]],

       [[ True, False],
        [ True,  True],
        [ True, False],
        [False, False]],

       [[ True,  True],
        [ True, False],
        [ True, False],
        [False, False]]])


np.isclose(abs(B-A[:, None]), 0).all(2)

array([[False, False, False,  True],
       [ True, False, False, False],
       [False, False,  True, False],
       [ True, False, False, False],
       [False,  True, False, False],
       [ True, False, False, False]])
mozway
  • 194,879
  • 13
  • 39
  • 75