0

In Python, I can use list.index to find the index of an element, e.g. [1,2,3,4].index(1) returns 0, since the element 1 occurs at position 0. I'd like to do this with multi-dimensional arrays. That is, I'd like to be able to write something like

x = np.array([[0, 1, 2],
              [3, 4, 5]])
y = np.array([0, 1, 2])
print(x.index(y))

The output should be 0, because again the target element is in the first position.

Using the built-in list.index method doesn't work because the == operator for numpy arrays returns an array rather than a boolean. And np.argwhere doesn't do any broadcasting. I know I could always do

idx = 0
while idx < x.shape[0] and (x[idx] != y).any():
  idx += 1
print(idx)

but that feels so clumsy!

0

1 Answer 1

1

There are several ways. Following this example (Find matching rows in 2 dimensional numpy array):

>>> np.where((x == y).all(axis=1))
(array([0]),)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.