python - pandas 人类索引排序

标签 python pandas sorting

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

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()

产量

enter image description here

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

最佳答案

纯Python,带有已排序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

关于python - pandas 人类索引排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468195/

相关文章:

python - Pandas :删除连续重复

python - 获取 pandas 数据框中一列中 n 个单词的前 n/2 个

c - 从高到低排序输出

c# - 按另一个字符串列表对字符串列表进行排序

python - 减少 Python 代码中的 OSX say 命令量

python - 导入和构造 python 模块/类

python - 如何获取 Jinja2 模板中的参数列表

python - 虚拟机中的 pyAudio 和 PJSIP

python - 当 groupby 另一个时, Pandas 在组中获得最少的一列

iphone - 使用三种不同的排序选项对数组进行排序