日期时间值重置

时间:2018-03-06 06:32:41

标签: pandas date time pivot transpose

嗨我有一个带有以下列的数据框df,等等整个月的值。

    Timestamp               Count
0   2017-10-01 00:00:00     783
1   2017-10-01 01:00:00     662
2   2017-10-01 02:00:00     075
3   2017-10-01 03:00:00     272
4   2017-10-01 04:00:00     381

我想按每小时行的顺序排列值

需要输出

       Hour1   Hour2    Hour3 ......... Hour24
Day1   783     662       075  .........
Day2   ...................................

1 个答案:

答案 0 :(得分:0)

Timestamp使用pandas.pivot转换为datehour,最后添加add_prefixrename_axis

df = (pd.pivot(df['Timestamp'].dt.date, 
              df['Timestamp'].dt.hour + 1, 
              df['Count'])
        .add_prefix('Hour')
        .rename_axis(None)
        .rename_axis(None, axis=1))

备选方案为set_index unstack

df = (df.set_index([df['Timestamp'].dt.date, df['Timestamp'].dt.hour + 1])['Count']
        .unstack()
        .add_prefix('Hour')
        .rename_axis(None)
        .rename_axis(None, axis=1))

print (df)
            Hour1  Hour2  Hour3  Hour4  Hour5
2017-10-01    783    662     75    272    381