简体   繁体   English

在 pandas 数据框中添加小时到年月日数据

[英]Add hours to year-month-day data in pandas data frame

I have the following data frame with hourly resolution我有以下每小时分辨率的数据框

day_ahead_DK1
Out[27]: 
      DateStamp    DK1
0    2017-01-01  20.96
1    2017-01-01  20.90
2    2017-01-01  18.13
3    2017-01-01  16.03
4    2017-01-01  16.43
        ...    ...
8756 2017-12-31  25.56
8757 2017-12-31  11.02
8758 2017-12-31   7.32
8759 2017-12-31   1.86
type(day_ahead_DK1)
Out[28]: pandas.core.frame.DataFrame

But the current column DateStamp is missing hours.但是当前列DateStamp缺少小时数。 How can I add hours 00:00:00 , to 2017-01-01 for Index 0 so it will be 2017-01-01 00:00:00 , and then 01:00:00 , to 2017-01-01 for Index 1 so it will be 2017-01-01 01:00:00 , and so on, so that all my days will have hours from 0 to 23. Thank you!如何将小时数00:00:00添加到2017-01-01索引0所以它将是2017-01-01 00:00:00 ,然后是01:00:002017-01-01索引1所以它将是2017-01-01 01:00:00 ,依此类推,这样我所有的日子都会有从 0 到 23 的时间。谢谢!

The expected output:预期的 output:

day_ahead_DK1
Out[27]: 
      DateStamp            DK1
0    2017-01-01 00:00:00  20.96
1    2017-01-01 01:00:00  20.90
2    2017-01-01 02:00:00  18.13
3    2017-01-01 03:00:00  16.03
4    2017-01-01 04:00:00  16.43
        ...    ...
8756 2017-12-31 20:00:00  25.56
8757 2017-12-31 21:00:00  11.02
8758 2017-12-31 22:00:00   7.32
8759 2017-12-31 23:00:00   1.86

Use GroupBy.cumcount for counter with to_timedelta for hours and add to DateStamp column:使用GroupBy.cumcountto_timedelta小时计数器并添加到DateStamp列:

df['DateStamp'] = pd.to_datetime(df['DateStamp'])

df['DateStamp'] += pd.to_timedelta(df.groupby('DateStamp').cumcount(), unit='H')
print (df)
               DateStamp    DK1
0    2017-01-01 00:00:00  20.96
1    2017-01-01 01:00:00  20.90
2    2017-01-01 02:00:00  18.13
3    2017-01-01 03:00:00  16.03
4    2017-01-01 04:00:00  16.43
8756 2017-12-31 00:00:00  25.56
8757 2017-12-31 01:00:00  11.02
8758 2017-12-31 02:00:00   7.32
8759 2017-12-31 03:00:00   1.86

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM