You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas多列时间取整至最近小时报错,求解决方案

问题解决:Datetime列取整时的AttributeError错误

错误原因

你碰到的AttributeError: 'Timestamp' object has no attribute '_delegate_method',是因为错误使用了pd.Series.dt.round——dt是Pandas中datetime类型Series的专属访问器,必须通过具体的Series实例调用,不能直接用pd.Series.dt去调用方法。

正确解决方案

方案1:直接对DataFrame的datetime列批量操作(推荐)

转换为datetime类型后,可直接对目标列组成的DataFrame使用.dt访问器批量取整,写法最简洁:

import pandas as pd 

df= pd.DataFrame({
    'time1': ['2017-03-21 15:10:45', '2017-03-22 15:16:45', '2017-03-23 17:08:20'],
    'time2': ['2018-02-22 13:10:45', '2018-02-11 12:16:45', '2017-03-23 11:10:07'],
    'value': [2, 3,4 ] 
})

# 转换指定列为datetime类型
df[['time1', 'time2']] = df[['time1', 'time2']].apply(pd.to_datetime)

# 批量取整至最近小时
df[['time1', 'time2']] = df[['time1', 'time2']].dt.round('H')

print(df)

方案2:使用apply逐个处理列

如果坚持用apply,需在lambda中针对每个Series实例调用.dt.round():

# 替换取整部分的代码即可
df[['time1', 'time2']] = df[['time1', 'time2']].apply(lambda col: col.dt.round('H'))

运行结果

执行后会得到取整后的datetime列:

time1               time2  value
0 2017-03-21 15:00:00 2018-02-22 13:00:00      2
1 2017-03-22 15:00:00 2018-02-11 12:00:00      3
2 2017-03-23 17:00:00 2017-03-23 11:00:00      4

内容的提问来源于stack exchange,提问作者Leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:05:24