Python,关于子数组的排序数组 [英] Python, sort array with respect to a sub-array

查看:84
本文介绍了Python,关于子数组的排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

master_array = [[1. 2. 3. 4. 5.]
                [9. 8. 4. 5. 1.]]

我想对master_array进行排序第二个子数组,以便维持第一个子数组和第二个子数组之间的关系

I would like to sort the master_array with respect to the second sub-array so that the relationship between first sub-array and second sub-array is maintained

master_array = [[5. 3. 4. 2. 1.] 
                [1. 4. 5. 8. 9.]]

谢谢

推荐答案

将列表转换为numpy数组

Convert list to numpy array

>>> import numpy as np
>>> master_array = [[1.,2.,3.,4.,5.], [9.,8.,4.,5.,1.]]
>>> n=np.array(master_array)
>>> n
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 9.,  8.,  4.,  5.,  1.]])

为第二个数组分配索引值,因此取 n [1]

Assign index values for the second array so take n[1]

>>> temp=list(enumerate(n[1]))
>>> temp
[(0, 9.0), (1, 8.0), (2, 4.0), (3, 5.0), (4, 1.0)]

按数组元素对数组进行排序

sort the array with respect to array elements

>>> list1=sorted(temp,key=lambda x:x[1])
>>> list1
[(4, 1.0), (2, 4.0), (3, 5.0), (1, 8.0), (0, 9.0)]

从排序结果中获取所有索引并存储在单独的数组中

Take all the indexes from sorted result and store in a seperate array

>>> a=[i[0] for i in list1 ]
>>> a
[4, 2, 3, 1, 0]

在以下位置使用列索引numpy数组上的numpy

Use indexing of columns in numpy on the numpy array

>>> n[:,a]
array([[ 5.,  3.,  4.,  2.,  1.],
       [ 1.,  4.,  5.,  8.,  9.]])

这篇关于Python,关于子数组的排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆