Skip to main content
 首页 » 编程设计

python之根据不同的数组对随机生成的 Numpy 数组进行排序

2024年12月31日18tuyile006

我创建了 2 个变量。一个保存 200 个随机生成的年龄,另一个保存 200 个随机生成的标记。

from numpy import * 
age = random.random_integers(18,40, size=(1,200)) 
marks = random.random_integers(0,100, size=(1,200)) 

我想使用 NumPy 按年龄数组对标记数组进行排序。例如:

#random student ages 
[32 37 53 48 39 44 33 40 56 47] 
#random student marks 
[167 160 176 163 209 178 201 164 190 156] 
 
#sorted marked according to ages 
[32 33 37 39 40 44 47 48 53 56] 
[167 201 160 209 164 178 156 163 176 190] 

这是与this 类似的问题一。由于随机生成的元素,我不确定是否适用类似的解决方案。

请您参考如下方法:

一种方法是先通过 argsort 计算排序,然后使用它来索引您的输入数组::

import numpy as np 
 
np.random.seed(0) 
 
ages = np.random.randint(18, 40, size=10)   # [30 33 39 18 21 21 25 27 37 39] 
marks = np.random.randint(0, 100, size=10)  # [36 87 70 88 88 12 58 65 39 87] 
 
order = ages.argsort()                      # [3 4 5 6 7 0 1 8 2 9] 
 
print(ages[order])                          # [18 21 21 25 27 30 33 37 39 39] 
print(marks[order])                         # [88 88 12 58 65 36 87 39 70 87]