Python按字母顺序对数据框进行排序。

29

我想按学生姓名重新排序数据框。 有人有什么建议吗?

df = pd.DataFrame({
        'student': [
            'monica', 'nathalia', 'anastasia', 'marina', 'ema'
        ],

    'grade' : ['excellent', 'excellent', 'good', 'very good', 'good'
    ]
    })

    print (df)

                student   grade

        0       monica    excellent        
        1       nathalia  excellent         
        2       anastasia good        
        3       marina    very good          
        4       ema       good 

如果您想按字母顺序以及长度(从大到小)对数据框进行排序,您该如何做? - Madhur Yadav
1
我很高兴你问了这个问题!非常有帮助! - Ice Bear
6个回答

54

在pandas 0.17版本之前:

# Sort by ascending student name
df.sort('student')
# reverse ascending
df.sort('student', ascending=False)

与其他答案提到的一样,Pandas 0.17+:

# ascending
df.sort_values('student')
# reverse ascending
df.sort_values('student', ascending=False)

6
小提醒,不要忘记将排序后的数据框重新赋值。我曾经一直在想为什么代码不起作用,哈哈。 - Franva

13

pandas 0.19.2

df.sort_values(by=['contig', 'pos'], ascending=True)

# where contig and pos are the column names. So, you may change for yours.

注意: 如果您想更新同一数据框,则使用inplace非常重要。大多数人在何时使用/不使用inplace方面会感到困惑。

如果您想创建一个新的数据框。

df_sorted = df.sort_values(by=['contig', 'pos'], inplace=False, ascending=True)

+1 for the inplace。我曾经因为一些教程没有添加inplace而导致数据结构被重构,但是打印出来看起来仍然相同,这让我头疼不已。 - Hercislife

8
您可以使用sort_values方法对数据框进行排序。
df.sort_values('student')

3

尝试

df.sort_values(by='student')

或者,如果您想先使用Z:

df.sort_values(by='student', ascending=False)

3

pd.DataFrame.sort_values是显而易见的pandas选择。

然而,你可以使用numpy并重构。这将为您提供适度的性能提升。

a = df.student.values.astype(str).argsort()
pd.DataFrame(df.values[a], df.index[a], df.columns)

       grade    student
2       good  anastasia
4       good        ema
3  very good     marina
0  excellent     monica
1  excellent   nathalia

小数据测试
enter image description here

大数据测试
enter image description here


注:本文涉及IT技术内容,旨在介绍小数据和大数据测试。

1
我没想到对于这个更大的数据框,Pandas 的速度会慢近3倍... - MaxU - stand with Ukraine

1

如果你从一个csv文件中读取数据,你也可以做类似的操作。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接