[英]How to sort 3D array's inner 2d arrays with numpy?
How to sort each 2d array that are in 3d array?如何对 3d 数组中的每个二维数组进行排序?
I have an array of shape (10, 1000, 3)
我有一个形状数组
(10, 1000, 3)
I am trying do a reverse sort by last column in each subarray.我正在尝试按每个子数组中的最后一列进行反向排序。
Looping solution:循环解决方案:
result = []
for subarr2d in arr3d:
subarr2d_sorted = subarr2d[subarr2d[:, -1].argsort()][::-1]
result.append(subarr2d_sorted)
I want to do that in numpy alone?我想单独在 numpy 中这样做吗? Is it even possible?
甚至可能吗?
You could use numpy.sort
and choose the inner axis
to sort along.您可以使用
numpy.sort
并选择内axis
进行排序。
import numpy as np
result = np.random.randint(20, size=(3, 4, 3))
print(np.sort(result, axis=2))
# outputs
# [[[ 8 11 11]
# [ 2 11 16]
# [ 3 7 14]
# [ 7 12 12]]
# [[ 8 10 16]
# [ 0 6 14]
# [ 0 16 17]
# [ 0 14 19]]
# [[ 2 4 5]
# [ 3 4 4]
# [ 1 1 11]
# [ 0 8 17]]]
print(np.sort(result, axis=1))
#outputs
# [[[ 7 2 7]
# [11 3 11]
# [12 8 11]
# [16 12 14]]
# [[14 6 0]
# [16 8 0]
# [17 14 0]
# [19 16 10]]
# [[ 2 1 0]
# [ 3 4 1]
# [11 4 4]
# [17 8 5]]]
To get the sorted array in descending order you could use -np.sort(-result, axis=2)
and you may also want to check numpy.flip
要按降序获取排序数组,您可以使用
-np.sort(-result, axis=2)
并且您可能还需要检查numpy.flip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.