Python:为pandas timestamp增加小时数

时间:2016-06-21 22:03:15

标签: python datetime pandas dataframe timedelta

我将csv文件读入pandas dataframe 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个元素。我想将Hour的相应元素添加到TDate。

我尝试了以下内容:

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

但我得到错误,因为它似乎不会将数组作为参数。如何将Hour的每个元素添加到TDate的相应元素。

1 个答案:

答案 0 :(得分:16)

我认为您可以使用TDate添加到Hourunit='h'列转换to_timedelta

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