With
ad = np.array([ 0.5, 0.8, 0.9, 0.1])
cp = np.array([[2,3,1,1,2,0],[1,0,1,3,1,2],[1,1,1,1,1,1],[0,1,2,3,2,2]])
How can I get Numpy to give me the elements of ad
with the indexes of cp[0,:]
as first row (the indexes are [2,3,1,1,2,0]
so the first row should be [0.9, 0.1, 0.8, 0.8, 0.9, 0.5]
), the elements with the indexes of cp[1,:]
as second row etc.?
如何让Numpy给我带有cp [0,:]索引作为第一行的广告元素(索引是[2,3,1,1,2,0]所以第一行应该是[0.9] ,0.1,0.8,0.8,0.9,0.5]),指数为cp [1,:]的元素为第二行等?
So the result should be:
所以结果应该是:
[[0.9, 0.1, 0.8, 0.8, 0.9, 0.5],
[0.8, 0.5, 0.8, 0.1, 0.8, 0.9],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
[0.5, 0.8, 0.9, 0.1, 0.9, 0.9]]
Preferably, of course, in an efficient and elegant way.
当然,优选地,以有效和优雅的方式。
1 个解决方案
#1
1
NumPy arrays support broadcasting. It will broadcast ad
to the needed shape. So this
NumPy阵列支持广播。它会将广告广播到所需的形状。所以这
>>> ad[cp]
array([[ 0.9, 0.1, 0.8, 0.8, 0.9, 0.5],
[ 0.8, 0.5, 0.8, 0.1, 0.8, 0.9],
[ 0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
[ 0.5, 0.8, 0.9, 0.1, 0.9, 0.9]])
will work.
Alternatively, you can use np.take()
:
或者,您可以使用np.take():
>>> np.take(ad, cp)
array([[ 0.9, 0.1, 0.8, 0.8, 0.9, 0.5],
[ 0.8, 0.5, 0.8, 0.1, 0.8, 0.9],
[ 0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
[ 0.5, 0.8, 0.9, 0.1, 0.9, 0.9]])
#1
1
NumPy arrays support broadcasting. It will broadcast ad
to the needed shape. So this
NumPy阵列支持广播。它会将广告广播到所需的形状。所以这
>>> ad[cp]
array([[ 0.9, 0.1, 0.8, 0.8, 0.9, 0.5],
[ 0.8, 0.5, 0.8, 0.1, 0.8, 0.9],
[ 0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
[ 0.5, 0.8, 0.9, 0.1, 0.9, 0.9]])
will work.
Alternatively, you can use np.take()
:
或者,您可以使用np.take():
>>> np.take(ad, cp)
array([[ 0.9, 0.1, 0.8, 0.8, 0.9, 0.5],
[ 0.8, 0.5, 0.8, 0.1, 0.8, 0.9],
[ 0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
[ 0.5, 0.8, 0.9, 0.1, 0.9, 0.9]])