如何向 pandas 数据框列添加小时 [英] how to add hour to pandas dataframe column

查看:82
本文介绍了如何向 pandas 数据框列添加小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的pandas dataframe时间列.

I have a pandas dataframe time column like following.

 segments_data['time']
 Out[1585]: 
 0      04:50:00
 1      04:50:00
 2      05:00:00
 3      05:12:00
 4      06:04:00
 5      06:44:00
 6      06:44:00
 7      06:47:00
 8      06:47:00
 9      06:47:00

我想在上述时间栏添加5小时30分钟. 我正在用python进行跟踪.

I want to add 5 hours and 30 mins to above time column. I am doing following in python.

pd.DatetimeIndex(segments_data['time']) + pd.DateOffset(hours=5,minutes=30)

但这给我一个错误.

TypeError: object of type 'datetime.time' has no len()

请帮助.

推荐答案

这是一种过时的方法,主要是这里的问题是缺少对time对象的矢量化支持,因此您首先需要转换<使用combine将c1>转换为datetime,然后应用偏移并获取time组件:

This is a gnarly way of doing it, principally the problem here is the lack of vectorised support for time objects, so you first need to convert the time to datetime by using combine and then apply the offset and get the time component back:

In [28]:  
import datetime as dt  
df['new_time'] = df['time'].apply(lambda x: (dt.datetime.combine(dt.datetime(1,1,1), x,) + dt.timedelta(hours=3,minutes=30)).time())
df

Out[28]:
           time  new_time
index                    
0      04:50:00  08:20:00
1      04:50:00  08:20:00
2      05:00:00  08:30:00
3      05:12:00  08:42:00
4      06:04:00  09:34:00
5      06:44:00  10:14:00
6      06:44:00  10:14:00
7      06:47:00  10:17:00
8      06:47:00  10:17:00
9      06:47:00  10:17:00

这篇关于如何向 pandas 数据框列添加小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆