对 pandas 中的数据框列进行自然排序 [英] Natural sort a data frame column in pandas

查看:87
本文介绍了对 pandas 中的数据框列进行自然排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对熊猫DataFrame中的列应用自然排序顺序.我想排序的列可能包含重复项.我已经看到相关的自然排序Pandas DataFrame 问题,但是它涉及到对索引而不是任何列进行排序.

I would like to apply a natural sort order to a column in a pandas DataFrame. The columns that I would like to sort might contain duplicates. I have seen the related Naturally sorting Pandas DataFrame question, however it was concerning sorting the index, not any column.

示例

df = pd.DataFrame({'a': ['a22', 'a20', 'a1', 'a10', 'a3', 'a1', 'a11'], 'b': ['b5', 'b2', 'b11', 'b22', 'b4', 'b1', 'b12']})

     a    b
0  a22   b5
1  a20   b2
2   a1  b11
3  a10  b22
4   a3   b4
5   a1   b1
6  a11  b12

自然排序列a:

     a    b
0   a1  b11
1   a1   b1
2   a3   b4
3  a10  b22
4  a11  b12
5  a20   b2
6  a22   b5

自然排序列b:

     a    b
0   a1   b1
1  a20   b2
2   a3   b4 
3  a22   b5
4   a1  b11
5  a11  b12
6  a10  b22

推荐答案

您可以将值转换为有序的类别,其中类别按natsorted排序,然后使用sort_values:

You can convert values to ordered categorical with sorted catgories by natsorted and then use sort_values:

import natsort as ns

df['a'] = pd.Categorical(df['a'], ordered=True, categories= ns.natsorted(df['a'].unique()))
df = df.sort_values('a')
print (df)
     a    b
5   a1   b1
2   a1  b11
4   a3   b4
3  a10  b22
6  a11  b12
1  a20   b2
0  a22   b5


df['b'] = pd.Categorical(df['b'], ordered=True, categories= ns.natsorted(df['b'].unique()))

df = df.sort_values('b')
print (df)
     a    b
5   a1   b1
1  a20   b2
4   a3   b4
0  a22   b5
2   a1  b11
6  a11  b12
3  a10  b22

这篇关于对 pandas 中的数据框列进行自然排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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