【问题标题】:Python - Pandas - date manipulation over series - errorPython - Pandas - 对系列的日期操作 - 错误
【发布时间】: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

【问题讨论】:

    标签: python date pandas


    【解决方案1】:

    与其让Series 命名空间更加混乱(甚至对于与时间增量等无关的系列),还为日期和时间相关属性提供了一个“dt”访问器。

    代替days_diff.days,做

    days_diff.dt.days
    

    【讨论】:

      【解决方案2】:

      您的代码在 x[i]Timestampx[0] 实际上是 Series 的假设下工作,因为您有一个 MultiIndex

      既然你似乎并不关心MultiIndex,我建议你把它去掉。

      x = x.reset_index(drop=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        • 2017-07-14
        • 2022-11-22
        • 2012-10-11
        • 2015-09-14
        • 2018-03-15
        • 2022-01-19
        相关资源
        最近更新 更多