如何重置Pandas DataFrame中的时间戳为0起点并累计经过时长
实现代码
先确认time列为pandas datetime类型,再执行以下逻辑即可:
import pandas as pd # 若time列还不是时间格式,先执行转换 df['time'] = pd.to_datetime(df['time']) # 计算所有时间与首个时间戳的差值 time_delta = df['time'] - df['time'].iloc[0] total_seconds = time_delta.dt.total_seconds() # 拆分出各时间单位后格式化输出 hours = total_seconds // 3600 remaining_seconds = total_seconds % 3600 minutes = remaining_seconds // 60 seconds = remaining_seconds % 60 df['time_new'] = hours.astype(int).astype(str).str.zfill(2) + ":" + \ minutes.astype(int).astype(str).str.zfill(2) + ":" + \ seconds.apply(lambda x: f"{x:06.3f}")
效果说明
上述代码生成的time_new列完全符合要求:累计小时不会按24小时制截断,同时保留到毫秒级精度,和你给出的示例输出完全匹配。
内容的提问来源于stack exchange,提问作者Adler Müller
相关产品推荐
相关产品推荐

