如何按两列或更多列对python pandas中的dataFrame进行排序? [英] How to sort a dataFrame in python pandas by two or more columns?

查看:540
本文介绍了如何按两列或更多列对python pandas中的dataFrame进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含abc列的数据框,我想按b列的升序对数据框进行排序,而按c列的降序对数据框进行排序,我该如何这样吗?

Suppose I have a dataframe with columns a, b and c, I want to sort the dataframe by column b in ascending order, and by column c in descending order, how do I do this?

推荐答案

从0.17.0版本开始,

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])


您可以使用 sort的升序参数:


You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

例如:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1


如@renadeen所评论


As commented by @renadeen

默认情况下,排序不正确!因此,您应该将sort方法的结果分配给变量或在方法调用中添加inplace = True.

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

也就是说,如果您想将df1用作已排序的DataFrame:

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

这篇关于如何按两列或更多列对python pandas中的dataFrame进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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