I have a dataframe that looks like this:
Hour DayOfWeek
00 Friday 4
Wednesday 19
01 Friday 7
07 Saturday 1
Thursday 3
Tuesday 3
Wednesday 5
08 Friday 1
Monday 17
Thursday 10
Tuesday 16
Wednesday 8
and I want to make it into a dataframe like so:
Hour Sunday Monday Tuesday Wednesday Thursday
01 4 5 6 0 7
03 3 5 6 6 0
05 2 1 8 6 9
11 0 1 8 0 0
12 1 5 7 6 7
15 1 5 6 0 2
plus I want to fill the zeros in the hours of the day to be in range 0 untill 23.
it looks like some kind of an advanced indexing in dataframe and I don't know how to do it, any help will be thanksfull!
thank you
I think you need unstack
:
print (df.index)
MultiIndex(levels=[[0, 1, 7, 8],
['Friday', 'Monday', 'Saturday', 'Thursday', 'Tuesday', 'Wednesday']],
labels=[[0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3],
[0, 5, 0, 2, 3, 4, 5, 0, 1, 3, 4, 5]],
names=['Hour', 'DayOfWeek'])
print (df.unstack(fill_value=0))
DayOfWeek Friday Monday Saturday Thursday Tuesday Wednesday
Hour
0 4 0 0 0 0 19
1 7 0 0 0 0 0
7 0 0 1 3 3 5
8 1 17 0 10 16 8
and last add reindex
:
print (df.unstack(fill_value=0).reindex(np.arange(24), fill_value=0))
Hour
0 4 0 0 0 0 19
1 7 0 0 0 0 0
2 0 0 0 0 0 0
3 0 0 0 0 0 0
4 0 0 0 0 0 0
5 0 0 0 0 0 0
6 0 0 0 0 0 0
7 0 0 1 3 3 5
8 1 17 0 10 16 8
9 0 0 0 0 0 0
10 0 0 0 0 0 0
11 0 0 0 0 0 0
12 0 0 0 0 0 0
13 0 0 0 0 0 0
14 0 0 0 0 0 0
15 0 0 0 0 0 0
16 0 0 0 0 0 0
17 0 0 0 0 0 0
18 0 0 0 0 0 0
19 0 0 0 0 0 0
20 0 0 0 0 0 0
21 0 0 0 0 0 0
22 0 0 0 0 0 0
23 0 0 0 0 0 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.