Numpy:从索引在另一个数组中的数组中获取值

时间:2021-12-20 12:48:26

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.

我有一个包含一些值的mx1数组a。此外,我有一个nxk数组,比如b,包含0到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:

对于b中的每个索引值,我想从a获得相应的值。我可以用循环来做到这一点:

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.

是否有任何内置的numpy功能或技巧更优雅?这种方法对我来说有点愚蠢。 PS:最初,a和b是Pandas对象,如果有帮助的话。

2 个解决方案

#1


14  

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

田田!这只是一个[b]。 (另外,你可能希望randint调用的上限为3.)

#2


1  

Try iteration with a numpy.flatiter object:

尝试使用numpy.flatiter对象进行迭代:

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

#1


14  

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

田田!这只是一个[b]。 (另外,你可能希望randint调用的上限为3.)

#2


1  

Try iteration with a numpy.flatiter object:

尝试使用numpy.flatiter对象进行迭代:

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