pandas Python:为熊猫时间戳添加小时数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37955332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Adding hours to pandas timestamp
提问by Zanam
I read a csv file into pandas dataframe df
and I get the following:
我将一个 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'>
Both the Hour
and TDate
columns have 100 elements. I want to add the corresponding elements of Hour to TDate.
无论是Hour
和TDate
列有100个元素。我想将Hour 的相应元素添加到TDate。
I tried the following:
我尝试了以下方法:
import pandas as pd
from datetime import date, timedelta as td
z3 = pd.DatetimeIndex(df['TDate']).to_pydatetime() + td(hours = df['Hour'])
But I get error as it seems td doesn't take array as argument. How do I add each element of Hour
to corresponding element of TDate
.
但是我收到错误,因为 td 似乎没有将数组作为参数。如何将 的每个元素添加Hour
到TDate
.
回答by jezrael
I think you can add to column TDate
column Hour
converted to_timedelta
with unit='h'
:
我认为你可以添加到TDate
列Hour
转换to_timedelta
为unit='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