0
我工作的一个大熊猫据帧,我的专栏之一是日期(年月日),另一种是一个小时(HH:MM),我想将两者连接起来列一个时间戳或datetime64列,以便稍后将该列用作索引(对于时间序列)。这里的情况是:连接两个数据帧列作为一个时间戳
你有什么想法?经典pandas.to_datetime()似乎只有在列包含小时只工作,每天只和年仅...等...
我工作的一个大熊猫据帧,我的专栏之一是日期(年月日),另一种是一个小时(HH:MM),我想将两者连接起来列一个时间戳或datetime64列,以便稍后将该列用作索引(对于时间序列)。这里的情况是:连接两个数据帧列作为一个时间戳
你有什么想法?经典pandas.to_datetime()似乎只有在列包含小时只工作,每天只和年仅...等...
设置
df
Out[1735]:
id date hour other
0 1820 20140423 19:00:00 8
1 4814 20140424 08:20:00 22
解决方案
import datetime as dt
#convert date and hour to str, concatenate them and then convert them to datetime format.
df['new_date'] = df[['date','hour']].astype(str).apply(lambda x: dt.datetime.strptime(x.date + x.hour, '%Y%m%d%H:%M:%S'), axis=1)
df
Out[1756]:
id date hour other new_date
0 1820 20140423 19:00:00 8 2014-04-23 19:00:00
1 4814 20140424 08:20:00 22 2014-04-24 08:20:00
什么是这里的2列dtypes?如果第一列是一个STR然后'pd.to_datetime(DF [ '日期'] + DF [ '时间'],格式= '%Y%米%d%H:%M:%S')'应该工作 – EdChum
可能重复[组合日期和时间列使用Python熊猫](http://stackoverflow.com/questions/17978092/combine-date-and-time-columns-using-python-pandas) – IanS
对不起,我没有'提及: 'date'列是'int','hour'列已经是'datetime.time' – plalanne