Python Numpy:高效的矩阵索引
我有两个numpy阵列:Python Numpy:高效的矩阵索引,python,numpy,Python,Numpy,我有两个numpy阵列: A的形状是(k,4,2) B的形状是(n,12,2) 其中k和n是整数 B的系数是矩阵A的索引。i、 例如,B[0,1,:]是一个数组[k,l],我们确信A[k,l]存在 我想做的是构建一个与B大小相同的矩阵C,这样,对于所有I,j,C[I,j]=a[B[I,j,0],B[I,j,1] 有没有一种有效的方法 我尝试过像A[:,B],A[0,B],但都没有成功。我也可以用for循环来实现,但我认为用numpy实现会快得多 对于那些想尝试的人,我准备了一些启动代码(使用
的形状是A
(k,4,2)
的形状是B
(n,12,2)
k
和n
是整数
B
的系数是矩阵A
的索引。i、 例如,B[0,1,:]
是一个数组[k,l]
,我们确信A[k,l]
存在
我想做的是构建一个与B
大小相同的矩阵C
,这样,对于所有I,j
,C[I,j]=a[B[I,j,0],B[I,j,1]
有没有一种有效的方法
我尝试过像A[:,B]
,A[0,B]
,但都没有成功。我也可以用for
循环来实现,但我认为用numpy实现会快得多
对于那些想尝试的人,我准备了一些启动代码(使用k=n=2
来测试这些方法:
import numpy as np
a = np.array([[
[73, -25],
[97, -25],
[73, 107],
[97, 107]],
[[81, 43],
[86, 43],
[81, 50],
[86, 43]]
])
b = np.array(
[[[0, 2],
[0, 0],
[0, 3],
[0, 1],
[1, 0],
[1, 2],
[1, 1],
[1, 3],
[0, 0],
[0, 0],
[0, 0],
[0, 0]],
[[0, 3],
[0, 2],
[0, 1],
[0, 0],
[1, 0],
[1, 2],
[1, 1],
[1, 3],
[0, 0],
[0, 0],
[0, 0],
[0, 0]]]
)
#the answer should be :
c = np.array(
[[[73, 107],
[73, -25],
[97, 107],
[97, -25],
[81, 43],
[81, 50],
[86, 43],
[86, 50],
[73, -25],
[73, -25],
[73, -25],
[73, -25]],
[[97, 107],
[73, 107],
[97, -25],
[73, -25],
[81, 43],
[81, 50],
[86, 43],
[86, 50],
[73, -25],
[73, -25],
[73, -25],
[73, -25]],
]
)
希望你明白这一点,
提前感谢,
a[b[…,0],b[…,1]
你可以做
b[:,:,0]
而不是b[…,0]
,但后者适用于具有任意维度的数组,只要你的索引位于最后一个维度。a[b[…,0],b[…,1]
应该做预期的事情。你可以做b[:,:,0]
而不是b[…,0]
,但后者适用于具有任意维度的数组,只要你在最后一个维度上有索引。你几乎做到了:
C=A[B[:,:,0],B[:,:,1]]
但是你让我困惑了一分钟,因为你的测试c
几乎没有错误的值:
>>> a,b,c = ...
>>> C = a[b[:,:,0],b[:,:,1]]
>>> np.all([C[i,j]==a[b[i,j,0],b[i,j,1]] for i in range(2) for j in range(12)])
True
>>> C==c
array([[[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, False],
[ True, False],
[ True, True],
[ True, True],
[ True, True],
[ True, True]],
[[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, False],
[ True, False],
[ True, True],
[ True, True],
[ True, True],
[ True, True]]])
你差点就成功了:
C=A[B[:,:,0],B[:,:,1]]
但是你让我困惑了一分钟,因为你的测试c
几乎没有错误的值:
>>> a,b,c = ...
>>> C = a[b[:,:,0],b[:,:,1]]
>>> np.all([C[i,j]==a[b[i,j,0],b[i,j,1]] for i in range(2) for j in range(12)])
True
>>> C==c
array([[[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, False],
[ True, False],
[ True, True],
[ True, True],
[ True, True],
[ True, True]],
[[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, False],
[ True, False],
[ True, True],
[ True, True],
[ True, True],
[ True, True]]])
非常感谢!我更正了错误的值非常感谢!我更正了错误的值