星期几的排序栏?

时间:2019-12-16 02:49:17

标签: python python-3.x pandas data-science

我的df如下:

      day     value
    Friday      32
    Friday      32
    Monday      11
    Monday      22
    Saturday    44
    Saturday    25
    Sunday      77
    Sunday      88
    Thursday    88
    Thursday    88
    Tuesday     88
    Tuesday     88
    Wednesday   88
    Wednesday   88

如何按正确的工作日排序?

我尝试过:

weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

df.Weekday = pd.Categorical(df.day,categories=weekdays)

df = df.sort_values('day')

它可以运行,但不会更改输出,

谢谢

2 个答案:

答案 0 :(得分:1)

您刚刚遇到了一些迷惑:

df.Weekday = pd.Categorical(df.day,categories=weekdays)

应为:

df['Weekday'] = pd.Categorical(df.day,categories=weekdays)

df = df.sort_values('day) 

应为:

df = df.sort_values('Weekday') 

它有效!

答案 1 :(得分:0)

这里是一个calenderreindex的人:

import calendar
idx=(df['day'].map({v:k for k,v in dict(enumerate(calendar.day_name)).items()})
     .sort_values().index)
df.reindex(idx)

          day  value
2      Monday     11
3      Monday     22
10    Tuesday     88
11    Tuesday     88
12  Wednesday     88
13  Wednesday     88
8    Thursday     88
9    Thursday     88
0      Friday     32
1      Friday     32
4    Saturday     44
5    Saturday     25
6      Sunday     77
7      Sunday     88