向数据框中的datetime64列添加偏移量 [英] add offset to the datetime64 column in a data frame

查看:66
本文介绍了向数据框中的datetime64列添加偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这确实是一种快速的方法:

this is really a quick one:

我正在从q迁移到熊猫,我正在尝试向数据框'spy'的Date列中的每个项添加1 nano

i am migrating from q to pandas, i am trying to add 1 nano to each of the item in the Date column of the data frame 'spy'

>>> spy
<class 'pandas.core.frame.DataFrame'>
Int64Index: 126 entries, 0 to 125
Data columns (total 6 columns):
Date      126  non-null values
Open      126  non-null values
High      126  non-null values
Low       126  non-null values
Close     126  non-null values
Volume    126  non-null values
dtypes: datetime64[ns](1), float64(4), int64(1)

为了说明,我有这个1纳米

for illuatration, i have this 1 nano

ttt=np.datetime64(1,'ns')

然后我尝试做:

[x+ttt for x in spy['Date']]

我遇到以下错误:

Traceback (most recent call last):
  File "/tmp/py6868jTH", line 9, in <module>
    [x+ttt for x in spy['Date']]
TypeError: ufunc add cannot use operands with types dtype('O') and dtype('<M8[ns]')

有人能启发我这是怎么回事吗? ttt和x应该是同一类型,对吧?

can anyone enlight me what's wrong here? ttt and x should be of the same type, right?

谢谢!

推荐答案

您无法添加日期时间.您必须改用timedelta:

You can't add datetimes. You have to use timedelta instead:

>>> s  = pd.Series(pd.date_range('2013-11-11', periods=3, freq='D'))
>>> td = np.timedelta64(1,'ns')
>>> s
0   2013-11-11 00:00:00
1   2013-11-12 00:00:00
2   2013-11-13 00:00:00
dtype: datetime64[ns]
>>> s + td
0   2013-11-11 00:00:00.000000001
1   2013-11-12 00:00:00.000000001
2   2013-11-13 00:00:00.000000001
dtype: datetime64[ns]

这篇关于向数据框中的datetime64列添加偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆