python - 将元组索引转换为日期时间索引

标签 python datetime pandas tuples

我按月/日/年等对数据帧进行平均,并且在将索引从日期时间转换为元组时遇到了麻烦。我希望在 Datetime 中建立索引,这样我就可以将其导出到 Excel 中以供其他非 Python 用户使用,并且它仍然对时间戳有意义。

这就是我的 Df 的样子:

Index   Date Time       Value
1       1/26/2016 07:00 100000.0    
2       1/26/2016 07:00 1000000.0   
3       1/26/2016 14:46     98.52
6       1/26/2016 14:46     Nan
8       1/26/2016 14:48     100.94
11      1/26/2016 14:48     Nan

这是我遇到问题的代码片段:

df_cv_1_grouped = df_cv_1.set_index('Date Time',drop=False)
year_hour_means = df_cv_1_grouped.groupby(
    lambda x: (x.year, x.month, x.day, x.hour)).mean()

输出很棒,但索引现在是一个元组(“值”列不相关。)

Index               Value
(2016, 1, 26, 7)    1.5
(2016, 1, 26, 14)   22.7
(2016, 1, 26, 15)   125.3
(2016, 1, 26, 16)   288.5   

我似乎找不到一种方法以简单的方式将其恢复为日期时间(或保留在那里)。

最佳答案

我认为你可以转换index to_period , groupby通过 index (level=0) 然后转换 to_timestamp :

df_cv_1_grouped = df_cv_1.set_index('Date Time', drop=False)

df_cv_1_grouped = df_cv_1_grouped.to_period('H')
print (df_cv_1_grouped)
                           Date Time       Value
Date Time                                       
2016-01-26 07:00 2016-01-26 07:00:00   100000.00
2016-01-26 07:00 2016-01-26 07:00:00  1000000.00
2016-01-26 14:00 2016-01-26 14:46:00       98.52
2016-01-26 14:00 2016-01-26 14:46:00         NaN
2016-01-26 14:00 2016-01-26 14:48:00      100.94
2016-01-26 14:00 2016-01-26 14:48:00         NaN

year_hour_means1 = df_cv_1_grouped.groupby(level=0).mean()
print (year_hour_means1)
                      Value
Date Time                  
2016-01-26 07:00  550000.00
2016-01-26 14:00      99.73

print (year_hour_means1.index)
PeriodIndex(['2016-01-26 07:00', '2016-01-26 14:00'], 
dtype='int64', name='Date Time', freq='H')

year_hour_means1 = year_hour_means1.to_timestamp()
print (year_hour_means1)
                         Value
Date Time                     
2016-01-26 07:00:00  550000.00
2016-01-26 14:00:00      99.73

print (year_hour_means1.index)
DatetimeIndex(['2016-01-26 07:00:00', '2016-01-26 14:00:00'], 
dtype='datetime64[ns]', name='Date Time', freq=None)

Converting between representations .

关于python - 将元组索引转换为日期时间索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646829/

相关文章:

python - PyQt拦截不继承的关闭事件

mysql - CURTIME() SQL 问题

java - 在 Java 中节省纪元时间的最佳方法是什么?

javascript - 显示开始日期小于结束日期 - Datepicker

python - 通过读取多个文件来读取任一列中的值

python - 我在通过 SendGrid 发送电子邮件时在标题中添加了“回复”和“引用”,但它不起作用

python - Visual Studio IDE 中的键盘中断交互式 Python

Python - 从Excel列列表创建多个文件夹

python - 使用 pandas 在 python 中动态解析日期为日期时间

python - 如何在 Keras 中保存每个时期的预测数据