我有一个如下所示的数据框:
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
我想把它变成一个像这样的数据框:
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
加上我想在一天中的小时内填零,直到0,直到23。
它看起来像数据框中的某种高级索引,我不知道该怎么做,任何帮助都会感激不尽!
谢谢
答案 0 :(得分:0)
我认为你需要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
并上次添加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