Skip to main content
 首页 » 编程设计

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

2024年10月17日5dflying

我按月/日/年等对我的数据帧进行平均,但在将索引从日期时间转换为元组时遇到了麻烦。我想在 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 .