python - Pandas timedelta 重采样周失败

标签 python pandas resampling

真题

如这个小示例所示,我尝试每周对 pandas 数据框进行重新采样:

import datetime
import pandas as pd

df = pd.DataFrame([{
    'A' : datetime.datetime.now() - datetime.datetime.now(),
    'B' : 2
},{
    'A' : datetime.datetime.now() - datetime.datetime.now(),
    'B' : 3
}])

df = df.set_index('A')

df.resample('W', how="mean")

这会抛出一个AttributeError:

AttributeError: 'Week' object has no attribute 'nanos'

(注意:如果我按"D" 重新采样,问题就不会发生)

如果我改为将索引转换为日期时间:

df.index = pd.to_datetime(df.index.values)
df.resample('W', how="mean")

重采样也有效。
问题:有没有不依赖纳秒的pandas timedelta类型?
或者:你有比利用datetime获取timedelta更优雅的方法吗?


完整跟踪:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pandas/core/generic.py", line 3266, in resample
    return sampler.resample(self).__finalize__(self)
  File "/Library/Python/2.7/site-packages/pandas/tseries/resample.py", line 98, in resample
    rs = self._resample_timestamps(kind='timedelta')
  File "/Library/Python/2.7/site-packages/pandas/tseries/resample.py", line 272, in _resample_timestamps
    self._get_binner_for_resample(kind=kind)
  File "/Library/Python/2.7/site-packages/pandas/tseries/resample.py", line 122, in _get_binner_for_resample
    self.binner, bins, binlabels = self._get_time_delta_bins(ax)
  File "/Library/Python/2.7/site-packages/pandas/tseries/resample.py", line 236, in _get_time_delta_bins
    name=ax.name)
  File "/Library/Python/2.7/site-packages/pandas/tseries/tdi.py", line 167, in __new__
    closed=closed)
  File "/Library/Python/2.7/site-packages/pandas/tseries/tdi.py", line 235, in _generate
    index = _generate_regular_range(start, end, periods, offset)
  File "/Library/Python/2.7/site-packages/pandas/tseries/tdi.py", line 895, in _generate_regular_range
    stride = offset.nanos
AttributeError: 'Week' object has no attribute 'nanos'

版本

>>> pd.__version__
'0.16.2'
>>> np.__version__
'1.10.1'

最佳答案

我认为不同之处在于 pandas 使用 numpy 的 datetime64 而 python datetime 类有所不同。当你打电话时

df.index = pd.to_datetime(df.index.values)

您正在从创建的 datetime.datetime 对象转换为 resample 作为参数的 numpy.datetime64 对象。

关于python - Pandas timedelta 重采样周失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36624473/

相关文章:

python - 在 Ubuntu 上的 Tkinter Python 中将突出显示的文本分配/存储为变量

Python 向数组中添加一个项目

python - 使用日期逻辑创建假数据

python - 'nan' python pandas 中的未知列 'field list'

python-2.7 - 将 Pandas 中的每日数据转换为每周数据

python - 从异步中的两个协程中选择第一个结果

python - 在 django-profile 中添加字段 first_name 和 last_name

python - 从空 pickle 文件中解泡 Python 字典时出现 EOFerror

r - R中按行引导/重采样矩阵

通过簇替换重新采样