【问题标题】:Add Multiple sort on Dataframe one via list and other by date通过列表和其他按日期在 Dataframe 上添加多种排序
【发布时间】:2020-05-01 06:46:09
【问题描述】:

我有一个这样的数据框

Name    values   Status          CompletedOn
ac       100    Pending      2019-01-10T03:59:42.184+00:00
as       10     Pending      2019-06-10T03:59:42.184+00:00
sd       10     Closed       2019-12-10T03:59:42.184+00:00
es       10     Closed       2019-12-11T03:59:42.184+00:00
sg       5      Closed       2020-12-10T03:59:42.184+00:00
er       10     optional     2019-12-14T03:59:42.184+00:00
rw       10     optional     2019-12-15T03:59:42.184+00:00

我想根据 list vals=['pending','optional','Closed'] 和 Completed on Date 对应的状态对它们进行排序。

我试过sorting by a custom list in pandas 但也无法弄清楚根据日期对它们进行排序的方法。

所以输出的 Dataframe 会是这样的

Name    values   Status          CompletedOn
ac       100    Pending      2019-06-10T03:59:42.184+00:00
as       10     Pending      2019-01-10T03:59:42.184+00:00
er       10     optional     2019-12-15T03:59:42.184+00:00
rw       10     optional     2019-12-14T03:59:42.184+00:00
sg       5      Closed       2020-12-10T03:59:42.184+00:00
es       10     Closed       2019-12-11T03:59:42.184+00:00
sd       10     Closed       2019-12-10T03:59:42.184+00:00

有什么帮助吗?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    试一试,看看它是否适合您的用例:

    我们的想法是将 Status 列作为 category 数据类型,并在转换中包含类别订单。然后您可以对 Status 和 CompletedOn 进行排序,并包含升序参数

    #convert Status to category dtype
    df.Status = pd.Categorical(df.Status, categories = ['Pending','optional','Closed'])
    
    #sort columns with ascending options for the columns
    df.sort_values(['Status', 'CompletedOn'],ascending = [True,False])
    
          Name  values   Status            CompletedOn
    1     as    10      Pending     2019-06-10 03:59:42.184000+00:00
    0     ac    100     Pending     2019-01-10 03:59:42.184000+00:00
    6     rw    10     optional     2019-12-15 03:59:42.184000+00:00
    5     er    10     optional     2019-12-14 03:59:42.184000+00:00
    4     sg    5      Closed       2020-12-10 03:59:42.184000+00:00
    3     es    10     Closed       2019-12-11 03:59:42.184000+00:00
    2     sd    10     Closed       2019-12-10 03:59:42.184000+00:00
    

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多