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