【发布时间】:2016-02-14 15:05:03
【问题描述】:
我是 Python 新手,遇到以下问题:
我在 Pandas 中创建了以下一系列日期:
x:
0 0 2016-09-19
1 2016-12-19
2 2016-05-17
3 2016-08-17
4 2016-02-17
..............
.............
..............
28 2016-09-13
29 2016-04-18
30 2016-05-17
31 2016-06-17
32 2016-05-17
33 2016-06-17
34 2016-04-18
dtype: datetime64[ns]
>>> type(x)
<class 'pandas.core.series.Series'>
我想用我的函数修改:
def new_date(x):
todaysdate = time.strftime("%m-%d-%Y")
todaysdate = pandas.to_datetime(todaysdate)
days_diff = x - todaysdate
days_diff = days_diff.days
if (days_diff < 14):
newdate = x + datetime.timedelta(days = 14)
return(newdate)
else:
return(x)
此函数检查 x 中的日期是否距离今天不到 14 天,如果是,则将 x 中给定的日期增加 14 天。这里我想覆盖 x 本身的日期。
该函数适用于 x 中的单个元素:
>>> new_date(x[4])
Timestamp('2016-03-02 00:00:00')
但是在 x 上循环时,我收到了这个错误:
>>> for i in range(0, len(x)):
... x[i] = new_date(x[i])
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 5, in new_date
File "/usr/lib/python3/dist-packages/pandas/core/generic.py", line 1843, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'days'
我在这里做错了什么? 任何指针都非常感谢。提前致谢,
Bd
【问题讨论】: