python - python - 如何按两列或多列对python pandas中的dataFram

假设我有一个包含 abc 列的数据框,我想按列 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 - 如何按两列或多列对python pandas中的dataFrame进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141558/

相关文章:

linux - 如何更改 Linux 中打开文件的数量限制?

linux - 增加 Linux 中 TCP/IP 连接的最大数量

python - 将 numpy dtypes 转换为原生 python 类型

python - 如何在正则表达式中使用变量?

linux - fork()、vfork()、exec()和clone()的区别

linux - `set -x` 有什么作用?

python - 在 TensorFlow 中,Session.run() 和 Tensor.eva

python - 如何并行化一个简单的 Python 循环?

linux - 遍历带有空格的文件列表

python - 访问列表的多个元素知道它们的索引