【问题标题】:How to sort with predetermined order in Pandas [duplicate]如何在熊猫中按预定顺序排序[重复]
【发布时间】: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 始终介于 -22 之间

我想按以下模式对high 的值进行排序:

首先,将所有0 分组并按日期等对其他值进行排序。

按以下顺序对high 值进行排序:

0
1
-1
2
-2

如果它足够灵活,我可以在需要时更改订单,那将是最好的。

我知道如何通过这样做对ascdesc 进行排序:

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


【解决方案1】:

您需要将high 定义为Categorical Series,并选择order

order = [0 , 1, -1, 2, -2]
df['high'] = pd.Categorical(df['high'], order)
df.sort_values(['high', 'date'])

输出:

        date    high
3   2018-01-04  0
1   2018-01-02  1
4   2018-12-31  1
0   2018-01-01  -1
2   2018-01-03  -2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多