NumPy数组使用argsort置换列3D矩阵 [英] NumPy array permute columns 3D matrix with argsort
问题描述
我需要用从argsort
获得的2D
置换矩阵pi
对矩阵A
(3D
矩阵乘axis
0)中的列元素进行置换,该矩阵包含所有列的新索引.
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.
通过在矩阵A
(A[pi]
)上的应用置换矩阵pi
,我将获得一个具有新形状的4D
矩阵.例如,A
的形状为(2,3,4),A[pi]
的形状为(2,3,3,4).
By application permutation matrix pi
on the matrix A
(A[pi]
) I will get a 4D
matrix with new shape. For example, the shape of A
is (2,3,4) and the shape of A[pi]
is (2,3,3,4).
我能够使用以下命令从A[pi]
中提取所需的排序矩阵:
I am able to extract the required sorted matrix from A[pi]
using the command:
swapaxes (diagonal(A[pi], axis1=2, axis2=1),1,2)
但是它似乎太复杂且太慢.
But it seems to be too complicated and slow.
还有另一种优雅的解决方案吗?
示例:
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]
输出:
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]]])
这篇关于NumPy数组使用argsort置换列3D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!