Python中按其他数组排序索引排序数组

2024-04-24 12:55:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点困难。我正在尝试将python中的一些代码矢量化,以使其更快。我有一个数组,我排序(A)并得到索引列表(Ind)。我有另一个数组(B),我想按索引列表排序,而不使用循环,我认为这会限制计算。在

A = array([[2, 1, 9],
           [1, 1, 5],
           [7, 4, 1]])
Ind = np.argsort(A)

这是Ind的结果:

^{pr2}$

B是我想按Ind排序的数组:

B = array([[ 6,  3,  9],
           [ 1,  5,  3],
           [ 2,  7, 13]])

我想使用Ind重新排列B中的元素(按A行索引排序的B行):

B = array([[ 3,  6,  9],
           [ 1,  5,  3],
           [13,  7,  2]])

有什么想法吗?我很乐意得到任何好的建议。我想说的是我使用了数百万个值,我的意思是30000*5000的数组。在

干杯, 罗伯特


Tags: 代码元素列表排序np数组array矢量化
1条回答
网友
1楼 · 发布于 2024-04-24 12:55:56

我会这样做:

import numpy as np
from numpy import array

A = array([[2, 1, 9],
           [1, 1, 5],
           [7, 4, 1]])
Ind = np.argsort(A)

B = array([[ 3,  6,  9],
           [ 1,  5,  3],
           [13,  7,  2]])

# an array of the same shape as A and B with row numbers for each element
rownums = np.tile(np.arange(3), (3, 1)).T

new_B = np.take(B, rownums * 3 + Ind)
print(new_B)
# [[ 6  3  9]
#  [ 1  5  3]
#  [ 2  7 13]]

您可以将幻数3替换为数组形状。在

相关问题 更多 >