gpt4 book ai didi

python - python - 如何按两列或多列对python pandas中的dataFrame进行排序?

转载 作者:IT老高 更新时间:2023-10-28 12:20:09 58 4
gpt4 key购买 nike

假设我有一个包含 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/

58 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com