gpt4 book ai didi

python - 3d numpy 数组中特定类型的排序

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:54 24 4
gpt4 key购买 nike

在 3d numpy 数组(有 p 个面板,每个面板有 r 行和 c 列)中,我只想对特定面板的列进行排序,以便其他面板上的相应元素相应地重新排列。

不幸的是,我不熟悉不同类型排序的行话。我会通过一个例子来阐明我需要什么。

将A看成一个2*3*4的数组

A = array([[[   9, 20, 30, 11],
[ 100, 4, -1, 90]
[ 40, 15, -5, 34]],

[[ 0, 2, 3, 9],
[ -1, 12, 6, -3]
[ 1, -5, 7, 2]]]),

在对第二个面板的列进行排序之后:

A = array([[[ 100, 15, 30, 90],
[ 9, 20, -1, 34]
[ 40, 4, -5, 11]],

[[ -1, -5, 3, -3],
[ 0, 2, 6, 2]
[ 1, 12, 7, 9]]])

如您所见,只有第二个面板的列被排序(升序),第一个面板中的元素与第二个面板中的相应元素重新排列(但未排序!)。

最佳答案

import numpy as np

A = np.array([[[ 9, 20, 30, 11],
[ 100, 4, -1, 90],
[ 40, 15, -5, 34]],

[[ 0, 2, 3, 9],
[ -1, 12, 6, -3],
[ 1, -5, 7, 2]]])

I, J, K = np.ogrid[tuple(map(slice, A.shape))]
# I, J, K are the identity indices in the sense that (A == A[I, J, K]).all()
newJ = np.argsort(A[1], axis=0) # first axis of A[1] is second axis of A
print(A[I, newJ, K])

产量

[[[100  15  30  90]
[ 9 20 -1 34]
[ 40 4 -5 11]]

[[ -1 -5 3 -3]
[ 0 2 6 2]
[ 1 12 7 9]]]

关于python - 3d numpy 数组中特定类型的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com