简体   繁体   中英

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.

>>> 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 .)

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM