Skip to content Skip to sidebar Skip to footer

How To Index A Ndarray With Another Ndarray?

I am doing some machine learning stuff in python/numpy in which I want to index a 2-dimensional ndarray with a 1-D ndarray, so that I get a 1-D array with the indexed values. I got

Solution 1:

You want a 1D array, yet you included a reshape call whose only purpose is to take the array from the format you want to a format you don't want.

Stop reshaping the arange output. Also, you don't need to specify the 0 start value explicitly:

result = a[b, np.arange(a.shape[1])]

Solution 2:

You can just use np.diagonal to get what you want. No need of reshape or indexing. The tricky part here was to identify the pattern which you want to obtain which is basically the diagonal elements of a[b] matrix.

a = np.arange(50).reshape(10, 5) # Array to be indexed
b = np.arange(9, -1, -2) # Indexing array
print (np.diagonal(a[b]))
# [45 36 27 18  9]

As @user2357112 mentioned in the comments, the return of np.diagonal is read only. In my opinion, it would be a problem if you plan to append/modify the values to this final desired list. If you just want to print them or use them for some further indexing, it should be fine.

As per the docs

Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error.

In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.

If you don’t write to the array returned by this function, then you can just ignore all of the above.

Post a Comment for "How To Index A Ndarray With Another Ndarray?"