[英]NumPy array permute columns 3D matrix with argsort
I need to permute elements of columns in the matrix A
( 3D
matrix by axis
0) by 2D
permutation matrix pi
obtained from argsort
, that contains new indices for all columns. 我需要用从
argsort
获得的2D
置换矩阵pi
置换矩阵A
( axis
0的3D
矩阵)中列的元素,该矩阵包含所有列的新索引。
By application permutation matrix pi
on the matrix A
( A[pi]
) I will get a 4D
matrix with new shape. 通过应用置换矩阵
pi
上的矩阵A
( A[pi]
我将得到一个4D
与新的形状的矩阵。 For example, the shape of A
is (2,3,4) and the shape of A[pi]
is (2,3,3,4). 例如,形状
A
是(2,3,4)的形状和A[pi]
是(2,3,3,4)。
I am able to extract the required sorted matrix from A[pi]
using the command: 我能够使用以下命令从
A[pi]
提取所需的排序矩阵:
swapaxes (diagonal(A[pi], axis1=2, axis2=1),1,2)
But it seems to be too complicated and slow. 但这似乎太复杂和缓慢。
Is there another elegant solution? 还有另一种优雅的解决方案吗?
Example: 例:
print(A)
[[[ 73 701 2411 2414]
[ 5515 8292 8414 16135]
[ 100 1241 2146 2931]]
[[ 1335 1747 3418 6312]
[ 3788 5449 5753 9738]
[ 565 3038 3800 5430]]]
pi=argsort(Norm_order(A),0)
print(pi)
[[1, 0, 1],
[0, 1, 0]]
print(swapaxes(diagonal(A[pi],axis1=2,axis2=1),1,2))
[[[ 1335 1747 3418 6312]
[ 5515 8292 8414 16135]
[ 565 3038 3800 5430]]
[[ 73 701 2411 2414]
[ 3788 5449 5753 9738]
[ 100 1241 2146 2931]]]
Maybe a matter of taste, but I find the following a bit more readable: 也许是一个口味问题,但是我发现以下内容更具可读性:
i, j = np.ogrid[:3, :4]
A[pi[..., None], i, j]
Output: 输出:
array([[[ 1335, 1747, 3418, 6312],
[ 5515, 8292, 8414, 16135],
[ 565, 3038, 3800, 5430]],
[[ 73, 701, 2411, 2414],
[ 3788, 5449, 5753, 9738],
[ 100, 1241, 2146, 2931]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.