假设我有一个包含 a
、b
和 c
列的数据框,我想按列 b< 对数据框进行排序
升序排列,c
列降序排列,我该怎么做?
最佳答案
从 0.17.0 版本开始,sort
方法已弃用,取而代之的是 sort_values
. sort
在 0.20.0 版本中被完全删除。参数(和结果)保持不变:
df.sort_values(['a', 'b'], ascending=[True, False])
您可以使用 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 评论的那样
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:
df1 = df1.sort(['a', 'b'], ascending=[True, False])
或
df1.sort(['a', 'b'], ascending=[True, False], inplace=True)
关于python - 如何按两列或更多列对 python pandas 中的数据帧进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53064987/