Reputation: 1998
I have df as below:
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
How can I sort this in order of correct weekday?
I tried:
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
df.Weekday = pd.Categorical(df.day,categories=weekdays)
df = df.sort_values('day')
it runs but does not change output,
thanks
Upvotes: 1
Views: 522
Reputation: 75100
Here is one with calender
and 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
Upvotes: 0
Reputation: 7224
You just had a few mistypos:
df.Weekday = pd.Categorical(df.day,categories=weekdays)
should be:
df['Weekday'] = pd.Categorical(df.day,categories=weekdays)
and
df = df.sort_values('day)
should be:
df = df.sort_values('Weekday')
and it works!
Upvotes: 1