np.argsort 函数以排序顺序为您提供数组的索引 -- 使用索引 --
>>> ages = np.random.randint(low=20, high=60, size=10)
>>> heights = np.random.randint(low=150, high=200, size=10)
>>> ages
array([44, 35, 37, 39, 48, 24, 22, 25, 22, 59])
>>> heights
array([179, 195, 158, 189, 183, 185, 186, 187, 161, 175])
>>> ia = np.argsort(ages)
>>> ages[ia]
array([22, 22, 24, 25, 35, 37, 39, 44, 48, 59])
>>> heights[ia]
array([186, 161, 185, 187, 195, 158, 189, 179, 183, 175])
注意,在这种情况下,您可能会考虑使用结构化数组:
>>> mytype = np.dtype([('age',int), ('height', int)])
>>> data = np.array(list(zip(ages, heights)), dtype=mytype)
>>> data
array([(44, 179), (35, 195), (37, 158), (39, 189), (48, 183), (24, 185),
(22, 186), (25, 187), (22, 161), (59, 175)],
dtype=[('age', '<i8'), ('height', '<i8')])
现在您可以将“订单”参数传递给.sort:
>>> data.sort(order='age')
>>> data
array([(22, 161), (22, 186), (24, 185), (25, 187), (35, 195), (37, 158),
(39, 189), (44, 179), (48, 183), (59, 175)],
dtype=[('age', '<i8'), ('height', '<i8')])
但是,这并不完全等同于上面,因为它使用高度来打破关系,所以请注意,(22, 161) 在 (22, 186) 之前。