Skip to main content
 首页 » 编程设计

python之使用 lexsort(python)对基于字符串的数字进行排序

2024年10月01日9freeliver54

我有一个要排序的数组。有些条目是字符串,因此 numpy 将所有内容都视为字符串(包括数字)。总的来说这很好,我实际上在几个地方利用了它,但是在尝试对其进行排序时会导致一些问题。

基本上,当字符串长度不同时就会出现问题(因此,如果排序为 50、120、110,它将给出 110、120、50 而不是 50、110、120)。

下面是一个简单的例子来说明发生了什么;有谁知道如何克服这个问题(如果我可以将元素保留为字符串后排序那会很棒,但如果不能的话我也可以做到)。

import numpy as np 
 
 
spam = np.array( [ [ 'Graham', 550, 29 ], [ 'John', 90, 1 ], [ 'Terry G', 450, 20 ], \ 
                   [ 'Eric', 550, 30   ], [ 'Terry J', 450, 20 ], [ 'Michael', 520, 33 ] ] ) 
 
print( "Original:\n") 
print( spam ) 
print( "\n\nSorted:\n" ) 
 
 
spam = spam[ np.lexsort( ( spam[ :, 2 ], spam[ :, 1 ] ) ) ][ : : -1 ] 
 
print( spam ) 

如果缺少任何信息等,请随时询问。一如既往,提前感谢您的帮助,如果这是重复的,我们深表歉意(据我所知,搜索未返回任何相关结果)。

请您参考如下方法:

为 lexsort 转换为 int 类型,然后使用这些 lex 排序的索引索引到输入数组中 -

sidx = np.lexsort(( spam[ :, 2 ].astype(int), spam[ :, 1 ].astype(int))) 
    # Or simply np.lexsort(spam[ :, 2:0:-1].astype(int).T) 
spam_out = spam[sidx[::-1]] 

sample 运行-

In [450]: spam 
Out[450]:  
array([['Graham', '550', '29'], 
       ['John', '90', '1'], 
       ['Terry G', '450', '20'], 
       ['Eric', '550', '30'], 
       ['Terry J', '450', '20'], 
       ['Michael', '520', '33']],  
      dtype='|S7') 
 
In [451]: sidx = np.lexsort(( spam[ :, 2 ].astype(int), spam[ :, 1 ].astype(int))) 
 
In [452]: spam[sidx[::-1]] 
Out[452]:  
array([['Eric', '550', '30'], 
       ['Graham', '550', '29'], 
       ['Michael', '520', '33'], 
       ['Terry J', '450', '20'], 
       ['Terry G', '450', '20'], 
       ['John', '90', '1']],  
      dtype='|S7')