Skip to main content
 首页 » 编程设计

python之Pandas 人类分类指数

2024年10月01日8jackei

可能这个问题之前有人问过,但我找不到任何信息

df = pd.DataFrame( 
    {"i1":[1,1,1,1,2,4,4,2,3,3,3,3], 
     "i2":[1,3,2,2,1,1,2,2,1,1,3,2], 
     "d1":['c1','ac2','c3','c4','c5','c6','c7','c8','c9','c10','c11','a']} 
) 
df.set_index('d1', inplace=True) 
df.sortlevel() 

产量

显然这是不希望的。我想在最后有 c10 和 c11。如何为排序算法提供 key (例如拆分字符串和整数)?

请您参考如下方法:

纯 python,带有 sorted 和 key

您可以定义一个函数,以便将索引拆分为一对字母(作为字符串)和数字(作为整数):

d1 = ['c1','ac2','c3','c4','c5','c6','c7','c8','c9','c10','c11','a'] 
 
import re 
pattern = re.compile('([a-z]+)(\d*)', re.I) 
def split_index(idx): 
    m = pattern.match(idx) 
    if m: 
        letters = m.group(1) 
        numbers = m.group(2) 
        if numbers: 
            return (letters, int(numbers)) 
        else: 
            return (letters, 0) 

举个例子:

>>> split_index('a') 
('a', 0) 
>>> split_index('c11') 
('c', 11) 
>>> split_index('c1') 
('c', 1) 

然后您可以使用此函数作为键来按字典顺序对索引进行排序:

print(sorted(d1, key=split_index)) 
# ['a', 'ac2', 'c1', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11'] 

Pandas 排序

您可以使用 split_index 中的元组创建一个新的临时列,根据该列排序并将其删除:

import pandas as pd 
df = pd.DataFrame( 
    {"i1":[1,1,1,1,2,4,4,2,3,3,3,3], 
     "i2":[1,3,2,2,1,1,2,2,1,1,3,2], 
     "d1":['c1','ac2','c3','c4','c5','c6','c7','c8','c9','c10','c11','a']} 
) 
df['order'] = df['d1'].map(split_index) 
df.sort_values('order', inplace=True) 
df.drop('order', axis=1, inplace=True) 
df.set_index('d1', inplace=True) 
print(df) 

输出:

     i1  i2 
d1          
a     3   2 
ac2   1   3 
c1    1   1 
c3    1   2 
c4    1   2 
c5    2   1 
c6    4   1 
c7    4   2 
c8    2   2 
c9    3   1 
c10   3   1 
c11   3   3