numpy-np.lexsort的用法

官方文档:https://numpy.org/doc/stable/reference/generated/numpy.lexsort.html

官方给出的说明是:

numpy.lexsort(keys, axis=-1)
Perform an indirect stable sort using a sequence of keys.

Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, 
lexsort returns an array of integer indices that describes the sort order by multiple columns. 
The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. 
The keys argument must be a sequence of objects that can be converted to arrays of the same shape. 
If a 2D array is provided for the keys argument, it’s rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.

Parameters
keys(k, N) array or tuple containing k (N,)-shaped sequences
The k different “columns” to be sorted. The last column (or row if keys is a 2D array) is the primary sort key.

axisint, optional
Axis to be indirectly sorted. By default, sort over the last axis.

Returns
indices(N,) ndarray of ints
Array of indices that sort the keys along the specified axis.

这种排序方式,是根据给定参数从最后一个参数开始进行排序,如果最后一个参数给定的值相同,则根据倒数第二个参数进行排序,以此类推。

例子:

1.对字母进行排序:

surnames = ('Hertz',    'Galilei', 'Hertz')
first_names = ('Heinrich', 'Galileo', 'Gustav')
ind = np.lexsort((first_names, surnames))
print(ind)

"""
输出:
[1 2 0]
"""

首先按照surnames进行排序,字母G在H前面,'Galilei'排在第一位,剩余两个'Hertz'值相同,开始按照倒数第二个参数first_names进行排序,字母G在H前面,'Gustav'排在'Heinrich'前面,此时,两个参数中的三个值完成排序:'Galilei','Hertz','Hertz',分别对应下标[1, 2, 0]。

list1 = [surnames[i] + ", " + first_names[i] for i in ind]
print(list1)

"""
输出:
['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
"""

 2.对数字进行排序:

a = [1,5,1,4,3,4,4] # First column
b = [9,4,0,4,0,2,1] # Second column
ind = np.lexsort((b,a)) # Sort by a, then by b
print(ind)
print([(a[i],b[i]) for i in ind])

"""
输出:
[2 0 4 6 5 3 1]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
"""

首先按照a进行排序,a中值相同则按照b进行排序。

3.对array进行排序:

x = np.array([
    [2, 1, 5, 1, 7],
    [3, 7, 6, 5, 9],
    [1, 3, 3, 4, 10]
])
print(x)
ind = np.lexsort(x)
print(ind)

"""
输出:
[[ 2  1  5  1  7]
 [ 3  7  6  5  9]
 [ 1  3  3  4 10]]
[0 2 1 3 4]
"""

对array排序,是按照最后一行开始,一次倒数第二行、倒数第三行、以此类推的顺序进行排序。

 

感谢参考文章中的一段话:

参考:

https://charlesnord.github.io/2017/04/16/numpy-lexsort/

 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值