Python系列的日期处理

2024-04-25 01:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个Python新手,遇到了以下问题:

我在熊猫中创建了以下一系列日期:

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中的单个元素:

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

我做错什么了? 非常感谢你的指点。提前谢谢

屋宇署


Tags: 函数incorepandasnewdatetimedatetype
2条回答

与其更加混乱Series命名空间(甚至对于与timedelta无关的序列等),不如为日期和时间相关的属性提供“dt”访问器。你知道吗

与其days_diff.days,不如

days_diff.dt.days

您的代码是在这样的假设下工作的:x[i]Timestamp,而x[0]实际上是Series,因为您有一个MultiIndex。你知道吗

既然你似乎不在乎MultiIndex,我建议你把它扔掉。你知道吗

x = x.reset_index(drop=True)

相关问题 更多 >