Suppose I have
a = array([[1, 2], [3, 4]])
and
b = array([1,1])
I'd like to use b in index a, that is to do a[b] and get 4 instead of [[3, 4], [3, 4]]
I can probably do
a[tuple(b)]
Is there a better way of doing it?
Thanks
Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.
According the NumPy tutorial, the correct way to do it is:
a[tuple(b)]
Suppose you want to access a subvector of a
with n index pairs stored in b
like so:
b = array([[0, 0], ... [1, 1]])
This can be done as follows:
a[b[:,0], b[:,1]]
For a single pair index vector this changes to a[b[0],b[1]]
, but I guess the tuple
approach is easier to read and hence preferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With