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

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

问题描述

假设我有一个包含 abc 列的数据框,我想按 b<列对数据框进行排序/code> 升序,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 版本开始,sort 方法已被弃用,取而代之的是 sort_values.sort 在 0.20.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])

<小时>

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

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中的数据帧进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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