![](/img/trans.png)
[英]How can I sort each row of the 2d numpy-array by another 2d index-array?
[英]How to sort each row of a 3D numpy array by another 2D array?
我有一个二维点的二维 numpy 数组:
np.random.seed(0)
a = np.random.rand(3, 4, 2) # each value is a 2D point
我想按每个点的范数对每一行进行排序
norms = np.linalg.norm(a, axis=2) # shape(3, 4)
indices = np.argsort(norms, axis=0) # indices of each sorted row
现在我想创建具有相同的形状和值作为数组a
。 这将使每行二维点按其范数排序。
我怎样才能做到这一点?
我尝试了 np.take 和 np.take_along_axis 的变体,但没有成功。
例如:
np.take(a, indices, axis=1) # shape (3,3,4,2)
这样a
3次,一次在每一行indices
。 我想品尝a
只有一次。 indices
中的每一行都有应该从相应行中采样的列。
如果我理解正确,你想要这个:
norms = np.linalg.norm(a,axis=2) # shape(3,4)
indices = np.argsort(norms , axis=1)
np.take_along_axis(a, indices[:,:,None], axis=1)
您的示例的输出:
[[[0.4236548 0.64589411]
[0.60276338 0.54488318]
[0.5488135 0.71518937]
[0.43758721 0.891773 ]]
[[0.07103606 0.0871293 ]
[0.79172504 0.52889492]
[0.96366276 0.38344152]
[0.56804456 0.92559664]]
[[0.0202184 0.83261985]
[0.46147936 0.78052918]
[0.77815675 0.87001215]
[0.97861834 0.79915856]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.