1

Suppose I have

[[array([x1, y1]), z1]
 [array([x2, y1]), z2]
 ......
 [array([xn, yn]), zn]
]

And I want to find the index of array([x5, y5]). How can find effieciently using NumPy?

3
  • Why do you have a python list of 1D numpy arrays instead of just a 2D numpy array? Commented Aug 11, 2016 at 20:25
  • I was making Tic Tac Toe using reinforment learning so every row contains the board configuration (every board can be distinguished by 2 attributes) and the V(s) score Commented Aug 11, 2016 at 20:28
  • 1
    I don;t know if any numpy functions will save you since you have everything in an awkward mix of python lists and numpy arrays. Why not just standard python .index() Commented Aug 11, 2016 at 20:31

1 Answer 1

1

To start off, owing to the mixed data format, I don't think you can extract the arrays in a vectorized manner. Thus, you can use loop comprehension to extract the first element corresponding to the arrays from each list element as a 2D array. So, let's say A is the input list, we would have -

arr = np.vstack([a[0] for a in A])

Then, simply do the comparison in a vectorized fashion using NumPy's broadcasting feature, as it will broadcast that comparison along all the rows and look all matching rows with np.all(axis=1). Finally, use np.flatnonzero to get the final indices. Thus, the final peace of the puzzle would be -

idx = np.flatnonzero((arr == search1D).all(1))

You can read up on the answers to this post to see other alternatives to get indices in such a 1D array searching in 2D array problem.

Sample run -

In [140]: A
Out[140]: 
[[array([3, 4]), 11],
 [array([2, 1]), 12],
 [array([4, 2]), 16],
 [array([2, 1]), 21]]

In [141]: search1D = [2,1]

In [142]: arr = np.vstack([a[0] for a in A]) # Extract 2D array

In [143]: arr
Out[143]: 
array([[3, 4],
       [2, 1],
       [4, 2],
       [2, 1]])

In [144]: np.flatnonzero((arr == search1D).all(1)) # Finally get indices
Out[144]: array([1, 3])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.