【问题标题】:Sorting pandas dataframe by weekdays按工作日对熊猫数据框进行排序
【发布时间】:2019-04-10 20:50:09
【问题描述】:

如何按工作日名称对 DataFrame 进行排序?我不能使用 pd.to_datetime() 方法,因为我的日期不是数字。

    Date    Transactions
0   Friday  140.652174
1   Monday  114.000000
2   Saturday    208.826087
3   Sunday  140.565217
4   Thursday    118.217391
5   Tuesday     107.826087
6   Wednesday   105.608696

【问题讨论】:

    标签: python python-3.x pandas sorting dataframe


    【解决方案1】:

    您可以将列值转换为ordered categoricals,因此可以使用sort_values

    cats = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    df['Date'] = pd.Categorical(df['Date'], categories=cats, ordered=True)
    df = df.sort_values('Date')
    print (df)
            Date  Transactions
    1     Monday    114.000000
    5    Tuesday    107.826087
    6  Wednesday    105.608696
    4   Thursday    118.217391
    0     Friday    140.652174
    2   Saturday    208.826087
    3     Sunday    140.565217
    

    或者从Date 列创建索引,使用set_index,然后是reindex,最后是reset_index

    注意:
    解决方案仅在列值唯一的情况下才有效

    df = df.set_index('Date').reindex(cats).reset_index()
    print (df)
    
            Date  Transactions
    0     Monday    114.000000
    1    Tuesday    107.826087
    2  Wednesday    105.608696
    3   Thursday    118.217391
    4     Friday    140.652174
    5   Saturday    208.826087
    6     Sunday    140.565217
    

    【讨论】:

    • 为什么不使用df['column_name'].dt.weekday()
    • @pyd - 不确定是否理解,我认为如果输入数据是日期时间应该是可能的。
    • 哦...好吧@jezrael
    • 谢谢!尤其是展示如何重置索引
    • @Jedrzej - 非常感谢!
    【解决方案2】:

    calendar.day_name 用于分类数据:

    from calendar import day_name
    
    df['Date'] = pd.Categorical(df['Date'], categories=day_name, ordered=True)
    
    df = df.sort_values('Date')
    
    print(df)
    
            Date  Transactions
    1     Monday    114.000000
    5    Tuesday    107.826087
    6  Wednesday    105.608696
    4   Thursday    118.217391
    0     Friday    140.652174
    2   Saturday    208.826087
    3     Sunday    140.565217
    

    如果在您的文化中,星期一被认为是一周的第一天,您可以将一周中的日子轮换 n 天。例如:

    from collections import deque
    
    days = deque(day_name)
    days.rotate(1)
    
    print(days)
    
    deque(['Sunday', 'Monday', 'Tuesday', 'Wednesday',
           'Thursday', 'Friday', 'Saturday'])
    

    然后将categories=days 作为参数提供给pd.Categorical

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 1970-01-01
      • 2018-05-24
      • 2021-08-08
      • 1970-01-01
      • 2021-04-04
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多