我按月/日/年等对数据帧进行平均,并且在将索引从日期时间转换为元组时遇到了麻烦。我希望在 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)
关于python - 将元组索引转换为日期时间索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646829/