Python:将小时添加到 pandas 时间戳

Python: Adding hours to pandas timestamp

我将一个 csv 文件读入 pandas 数据框 df 并得到以下信息:

df.columns
Index([u'TDate', u'Hour', u'SPP'], dtype='object')
>>> type(df['TDate'][0])
<class 'pandas.tslib.Timestamp'>

type(df['Hour'][0])
<type 'numpy.int64'>

>>> type(df['TradingDate'])
<class 'pandas.core.series.Series'>
>>> type(df['Hour'])
<class 'pandas.core.series.Series'>

HourTDate 列都有 100 个元素。我想在TDate中加入Hour对应的元素

我尝试了以下方法:

import pandas as pd
from datetime import date, timedelta as td
z3 = pd.DatetimeIndex(df['TDate']).to_pydatetime() + td(hours = df['Hour'])

但我收到错误消息,因为 td 似乎没有将数组作为参数。如何将 Hour 的每个元素添加到 TDate.

的相应元素

我想你可以添加到第 TDateHour 转换 to_timedeltaunit='h':

df = pd.DataFrame({'TDate':['2005-01-03','2005-01-04','2005-01-05'],
                   'Hour':[4,5,6]})

df['TDate'] = pd.to_datetime(df.TDate)
print (df)
   Hour      TDate
0     4 2005-01-03
1     5 2005-01-04
2     6 2005-01-05

df['TDate'] +=  pd.to_timedelta(df.Hour, unit='h')
print (df)
   Hour               TDate
0     4 2005-01-03 04:00:00
1     5 2005-01-04 05:00:00
2     6 2005-01-05 06:00:00