Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: get values from array where indices are in another array

I have a mx1 array, a, that contains some values. Moreover, I have a nxk array, say b, that contains indices between 0 and m.

Example:

a = np.array((0.1, 0.2, 0.3))
b = np.random.randint(0, 3, (4, 4))

For every index value in b I want to get the corresponding value from a. I can do it with a loop:

c = np.zeros_like(b).astype('float')
n, k = b.shape
for i in range(n):
    for j in range(k):
        c[i, j] = a[b[i, j]]

Is there any built-it numpy function or trick that is more elegant? This approach looks a little dumb to me. PS: originally, a and b are Pandas objects if that helps.

like image 404
BayerSe Avatar asked Jun 24 '14 07:06

BayerSe


People also ask

How do you get the positions where elements of two arrays match in NumPy?

Method 3: Using array_equal() This array_equal() function checks if two arrays have the same elements and same shape.

How do you check if an array contains a value from another array Python?

How do you check if an array contains a value? The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if all elements of an array are in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

Can you access an array element by referring to the index?

Access Array ElementsYou can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


2 Answers

>>> a
array([ 0.1,  0.2,  0.3])
>>> b
array([[0, 0, 1, 1],
       [0, 0, 1, 1],
       [0, 1, 1, 0],
       [0, 1, 0, 1]])
>>> a[b]
array([[ 0.1,  0.1,  0.2,  0.2],
       [ 0.1,  0.1,  0.2,  0.2],
       [ 0.1,  0.2,  0.2,  0.1],
       [ 0.1,  0.2,  0.1,  0.2]])

Tada! It's just a[b]. (Also, you probably wanted the upper bound on the randint call to be 3.)

like image 138
user2357112 supports Monica Avatar answered Sep 24 '22 02:09

user2357112 supports Monica


Try iteration with a numpy.flatiter object:

a = np.array((0.1, 0.2, 0.3))
b = np.random.randint(0, 3, (4, 4))

c = np.array([a[i] for i in b.flat]).reshape(b.shape)
print(c)

array([[ 0.2,  0.2,  0.2,  0.1],
       [ 0.3,  0.3,  0.2,  0.1],
       [ 0.2,  0.1,  0.3,  0.3],
       [ 0.3,  0.3,  0.3,  0.1]])
like image 20
MaxPowers Avatar answered Sep 21 '22 02:09

MaxPowers