如何通过另一个 2D 数组对 3D numpy 数组的每一行进行排序?

Ela*_*oni 3 python arrays numpy numpy-ndarray

我有一个 2D 点的 2D numpy 数组:

np.random.seed(0)   
a = np.random.rand(3, 4, 2) # each value is a 2D point
Run Code Online (Sandbox Code Playgroud)

我想按每个点的范数对每一行进行排序

norms = np.linalg.norm(a, axis=2) # shape(3, 4)

indices = np.argsort(norms, axis=0) # indices of each sorted row
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个与 具有相同形状和值的数组a。每行 2D 点将按其范数排序。

我怎样才能做到这一点?

我尝试了 np.take 和 np.take_along_axis 的变体,但没有成功。

例如:

np.take(a, indices, axis=1) # shape (3,3,4,2)
Run Code Online (Sandbox Code Playgroud)

此采样a3 次,每行一次indices。我只想取样a一次。中的每一行都有indices应从相应行中采样的列。

Ehs*_*san 5

如果我理解正确的话,你想要这个:

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)
Run Code Online (Sandbox Code Playgroud)

您的示例的输出:

[[[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]]]
Run Code Online (Sandbox Code Playgroud)

  • @尼娜卡普雷斯。它在“None”索引处添加了一个新维度。`np.newaxis 都不是`。 (2认同)