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!
https://stackoverflow.com/questions/67363072/numpy-equivalent-to-list-index May 03, 2021 at 11:07AM
没有评论:
发表评论