本文介绍了如何按两列或更多列对python pandas中的dataFrame进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含a
,b
和c
列的数据框,我想按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版本开始, 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])
您可以使用 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
也就是说,如果您想将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进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!