1

I have a numpy array of arrays:

qv=array([[-1.075, -1.075, -3.   ],
       [-1.05 , -1.075, -3.   ],
       [-1.025, -1.075, -3.   ],
       ..., 
       [-0.975, -0.925, -2.   ],
       [-0.95 , -0.925, -2.   ],
       [-0.925, -0.925, -2.   ]])

And I want to determine if an array is contained in that 2-D array and return its index.

qt=array([-1.  , -1.05, -3.  ])

I can convert both arrays to lists and use the list.index() function:

qlist=qv.tolist()
ql=qt.tolist()
qindex=qlist.index(ql)

But I would like to avoid doing this because I think it will be a performance hit.

2
  • don't "think it will be a performance hit". measure. Commented May 6, 2013 at 23:27
  • 1
    I will. Once it becomes clear how to do it using numpy instead of lists. Commented May 6, 2013 at 23:29

1 Answer 1

3

This should do the trick,

import numpy as np
np.where((qv == qt).all(-1))

Or

import numpy as np
tol = 1e-8
diff = (qv - qt)
np.where((abs(diff) < tol).all(-1))

The second method might be more appropriate when floating point precision issues come into play. Also, there might be a better approach if you have many qt to test against. For example scipy.spatial.KDTree.

1
  • Hooray! +1 for floating point considerations. For my particular test set, %timeit in ipython shows that your method is 30.5 ns, vs 770 us for the list method. Thanks! Commented May 7, 2013 at 0:10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.