对熊猫中的数据框列进行自然排序

时间:2018-09-17 11:19:58

标签: python pandas dataframe natural-sort

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

示例

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

3 个答案:

答案 0 :(得分:2)

您可以将值转换为具有natsorted排序类别的有序categorical,然后使用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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

我们可以使用正则表达式提取列的文本和整数部分,然后使用它们进行排序。通过将其包装在函数中,您可以轻松地为每列分别进行操作:

def natural_sort(df, col):
    df[['_str', '_int']] = df[col].str.extract(r'([a-zA-Z]*)(\d*)')
    df['_int'] = df['_int'].astype(int)

    return df.sort_values(by=['_str', '_int']).drop(['_int', '_str'], axis=1)


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

print(natural_sort(df, 'a'))
print(natural_sort(df, 'b'))

打印:

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

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