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

Bay*_*rSe 6 python numpy pandas

我有一个包含一些值的mx1数组a.此外,我有一个nxk数组,比如b,包含0到m之间的索引.

例:

a = np.array((0.1, 0.2, 0.3))
b = np.random.randint(0, 3, (4, 4))
Run Code Online (Sandbox Code Playgroud)

对于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]]
Run Code Online (Sandbox Code Playgroud)

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

use*_*ica 16

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

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