【问题标题】:Accessing `.days` for a pandas Series of timedeltas访问 `.days` 以获得 pandas 的 timedeltas 系列
【发布时间】:2017-08-02 18:33:53
【问题描述】:

pandas TimedeltaIndex 有一个属性days,可用于其他普通数据类型(float64 等)的操作:

import pandas as pd
from pandas.tseries import offsets
idx1 = pd.date_range('2017-01', periods=10)
idx2 = idx1 + offsets.MonthEnd(1)
tds = idx2 - idx1

print(tds.days - 2)
Int64Index([28, 27, 26, 25, 24, 23, 22, 21, 20, 19], dtype='int64')

但是当tds 被转换为一个Series(显式地,或者作为DataFrame 列)时,它就失去了这个属性。

print(pd.Series(tds).days)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-115-cb20b4d368f4> in <module>()
----> 1 print(pd.Series(tds).days)

C:\Users\bsolomon\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   3079             if name in self._info_axis:
   3080                 return self[name]
-> 3081             return object.__getattribute__(self, name)
   3082 
   3083     def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'days'

访问.days 需要转换回Index

print(pd.Index(pd.Series(tds)).days)
Int64Index([30, 29, 28, 27, 26, 25, 24, 23, 22, 21], dtype='int64')

有没有比上面的转换更直接的方法来访问这个属性?

【问题讨论】:

    标签: python python-3.x pandas timedelta


    【解决方案1】:

    使用.dt访问器:

    print(pd.Series(tds).dt.days)
    

    输出:

    0    30
    1    29
    2    28
    3    27
    4    26
    5    25
    6    24
    7    23
    8    22
    9    21
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 2015-02-04
      • 2014-11-18
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      相关资源
      最近更新 更多