我的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')
它可以运行,但不会更改输出,
谢谢
答案 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)
这里是一个calender
和reindex
的人:
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