我的数据帧如下:
StationID DateTime Channel Count
0 1 2017-10-01 00:00:00 1 212
1 1 2017-10-01 00:00:00 2 157
2 1 2017-10-01 00:00:00 3 258
3 1 2017-10-01 00:00:00 4 158
4 1 2017-10-01 01:00:00 1 154
5 1 2017-10-01 01:00:00 2 141
6 1 2017-10-01 01:00:00 3 213
7 1 2017-10-01 01:00:00 4 132
8 1 2017-10-01 02:00:00 1 153
9 1 2017-10-01 02:00:00 2 135
10 1 2017-10-01 02:00:00 3 187
11 1 2017-10-01 02:00:00 4 127
12 1 2017-10-01 03:00:00 1 199
13 1 2017-10-01 03:00:00 2 87
14 1 2017-10-01 03:00:00 3 129
15 1 2017-10-01 03:00:00 4 92
16 1 2017-10-01 04:00:00 1 59
我希望按列每小时转换数据框
StationID Date Channel Hour1 Hour2 ....... Hour24
1 2017-10-01 1 212 154 ...........
1 2017-10-01 2 157 141 ...........
等等
答案 0 :(得分:2)
请注意,您使用unstack
df['Hour']=df.DateTime.dt.hour
df['Date']=df.DateTime.dt.date
df.set_index(['Date','StationID','Channel','Hour'])['Count'].unstack().reset_index()
Out[110]:
Hour Date StationID Channel 0 1 2 3 4
0 2017-10-01 1 1 212.0 154.0 153.0 199.0 59.0
1 2017-10-01 1 2 157.0 141.0 135.0 87.0 NaN
2 2017-10-01 1 3 258.0 213.0 187.0 129.0 NaN
3 2017-10-01 1 4 158.0 132.0 127.0 92.0 NaN
或prefix
的{{1}}
Hour