numpy:从数组中获取索引位于另一个数组中的值 [英] Numpy: get values from array where indices are in another array

查看:68
本文介绍了numpy:从数组中获取索引位于另一个数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例:

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

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

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

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

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

多田!只是a[b]. (此外,您可能希望randint调用的上限为3.)

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

这篇关于numpy:从数组中获取索引位于另一个数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆