Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing numpy array with another numpy array

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

like image 575
xster Avatar asked Apr 01 '11 01:04

xster


People also ask

How do I connect two NumPy arrays?

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.

What is NumPy fancy indexing?

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.


2 Answers

According the NumPy tutorial, the correct way to do it is:

a[tuple(b)] 
like image 53
JoshAdel Avatar answered Sep 27 '22 20:09

JoshAdel


Suppose you want to access a subvector of a with n index pairs stored in blike 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.

like image 29
Brandlingo Avatar answered Sep 27 '22 20:09

Brandlingo