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

问题描述

我将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个元素.我想将Hour的相应元素添加到TDate.

我尝试了以下操作:

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_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

I read a csv file into pandas dataframe df and I get the following:

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.

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.

解决方案

I think you can add to column TDate column Hour converted to_timedelta with 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

这篇关于Python:向 pandas 时间戳添加时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 13:35