Skip to main content
 首页 » 编程设计

python之按小时向下舍入日期时间列

2025年05月04日20kuangbin

11/22/2017 10:00  14.442473 
11/22/2017 10:05  19.446146 
11/22/2017 10:10  49.382300 
11/22/2017 10:15  51.216980 
11/22/2017 10:20  50.674092 
11/22/2017 10:25  14.893244 
11/22/2017 10:30  27.191617 
11/22/2017 10:35  19.826802 
11/22/2017 10:40   9.996578 
11/22/2017 10:45   7.929272 
11/22/2017 10:50  22.770500 
11/22/2017 10:55  32.611105 

假设我有上面的数据,我对所有列 A 的输出应该是:11/22/2017 10:00,汇总函数将不起作用,因为 10:30 之后的时间被视为 11:00,因此需要帮助来忽略分钟和秒,以便为进一步分析准备好我的确切数据。

请您参考如下方法:

开始于 -

print(s) 
 
11/22/2017 10:00    14.442473 
11/22/2017 10:05    19.446146 
11/22/2017 10:10    49.382300 
11/22/2017 10:15    51.216980 
11/22/2017 10:20    50.674092 
11/22/2017 10:25    14.893244 
11/22/2017 10:30    27.191617 
11/22/2017 10:35    19.826802 
11/22/2017 10:40     9.996578 
11/22/2017 10:45     7.929272 
11/22/2017 10:50    22.770500 
11/22/2017 10:55    32.611105 
Name: Data, dtype: float64 

首先,使用 pd.to_datetime 将索引转换为日期时间索引 -

df.index = pd.to_datetime(df.index, errors='coerce') 

假设日期是此 Series 索引的一部分,使用 floor 函数,日期时间的频率为每小时 -

s.index = s.index.floor('H') 
print(s) 
 
2017-11-22 10:00:00    14.442473 
2017-11-22 10:00:00    19.446146 
2017-11-22 10:00:00    49.382300 
2017-11-22 10:00:00    51.216980 
2017-11-22 10:00:00    50.674092 
2017-11-22 10:00:00    14.893244 
2017-11-22 10:00:00    27.191617 
2017-11-22 10:00:00    19.826802 
2017-11-22 10:00:00     9.996578 
2017-11-22 10:00:00     7.929272 
2017-11-22 10:00:00    22.770500 
2017-11-22 10:00:00    32.611105 
Name: Data, dtype: float64 

如果要在数据框列(例如,Date)上应用 floor 函数,请使用 .dt 访问器 -

df['Date'] = pd.to_datetime(df['Date']).dt.floor('H')