# 自然排序pandas中的数据框列[重复]

##### 问题描述投票：0回答：3

``````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    b
0   a1  b11
1   a1   b1
2   a3   b4
3  a10  b22
4  a11  b12
5  a20   b2
6  a22   b5
``````

``````     a    b
0   a1   b1
1  a20   b2
2   a3   b4
3  a22   b5
4   a1  b11
5  a11  b12
6  a10  b22
``````
python pandas dataframe natural-sort
##### 3个回答
2

``natsorted``

``sort_values``

0

``````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
``````

0

``````df.sort_values(by=['a'])
``````

``````df.sort_values(by=['b'])
``````