【发布时间】:2019-07-29 18:48:37
【问题描述】:
我的数据集df 如下所示:
date high
2018-01-01 -1
2018-01-02 1
2018-01-03 -2
2018-01-04 0
...., ....
2018-12-31 1
在哪里,
-2 >= high <= 2
high 始终介于 -2 和 2 之间
我想按以下模式对high 的值进行排序:
首先,将所有0 分组并按日期等对其他值进行排序。
按以下顺序对high 值进行排序:
0
1
-1
2
-2
如果它足够灵活,我可以在需要时更改订单,那将是最好的。
我知道如何通过这样做对asc 或desc 进行排序:
df.sort_values(by='high', ascending=False)
您能帮我解决如何使用预定值进行排序吗?
【问题讨论】:
-
df.sort_values(['high', 'date'], ascending=[True,True])? -
df = df.sort_values(['high', 'date'], ascending=[True,True])
-
你能想出一个minimal reproducible example吗?
-
建议的代码完全符合您的描述。我认为您没有正确解释您的问题。
-
@Erfan 很好的解决方案。但这不满足 OP 对
"It would be best if it's flexible enough that I can change the order if required."的要求。在这种情况下最好使用Categorical Series。
标签: python-3.x pandas dataframe