python - Pandas 重新采样引发由日期时间对象组成的索引的类型错误

标签 python python-3.x pandas dataframe

我正在尝试对一个非常简单的数据帧进行重新采样,但失败并出现以下异常:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

我阅读了 pandas API 文档并查看了数十个示例,但我无法弄清楚我做错了什么。

# %%
import pandas as pd
print(f"pandas version: {pd.__version__}\n\n")

data = pd.DataFrame({"created": ['2019-03-07T11:01:07.361+0000',
                                 '2019-06-05T15:09:51.203+0100',
                                 '2019-06-05T15:09:51.203+0100'],
                     "value": [10, 20, 30]})

# %%
print(f"original type: {type(data.created[0])}\n")
data.info()

# %%
data.created = pd.to_datetime(data.created)

# %%
print(f"updated type: {type(data.created[0])}\n")
data.info()

# %%
data.set_index("created", inplace=True)
data.info()

# %%
data.resample("D").mean()

这是结果

Pandas 版本:0.24.2

original type: <class 'str'>

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
created    3 non-null object
value      3 non-null int64
dtypes: int64(1), object(1)
memory usage: 128.0+ bytes
updated type: <class 'datetime.datetime'>

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
created    3 non-null object
value      3 non-null int64
dtypes: int64(1), object(1)
memory usage: 128.0+ bytes
<class 'pandas.core.frame.DataFrame'>
Index: 3 entries, 2019-03-07 11:01:07.361000+00:00 to 2019-06-05 15:09:51.203000+01:00
Data columns (total 1 columns):
value    3 non-null int64
dtypes: int64(1)
memory usage: 48.0+ bytes
Traceback (most recent call last):
  File "c:/Users/me/dev/misc/index.py", line 32, in <module>
    data.resample("D").mean()
  File "C:\Users\me\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py", line 8155, in resample
    base=base, key=on, level=level)
  File "C:\Users\me\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\resample.py", line 1250, in resample
    return tg._get_resampler(obj, kind=kind)
  File "C:\Users\me\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\resample.py", line 1380, in _get_resampler
    "but got an instance of %r" % type(ax).__name__)
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'Index, but got an instance of 'Index'

最佳答案

让我们从一些原则开始:

  1. 要进行重新采样,源SeriesDataFrame必须具有例如 DatetimeIndex(不是“普通”索引)。

  2. 您可以为该列设置索引,但为此,所有日期时间 元素必须位于相同时区(您的数据不是)。

因此您可以按照以下步骤操作:

  1. 创建的列转换为日期时间(代码的一部分)时, 传递utc=True来“统一”时区:

    data.created = pd.to_datetime(data.created, utc=True)
    
  2. 设置索引,然后您可以自由地重新采样:

    data.set_index('created').resample("D").mean()
    

另一个选项:您可以传递on参数,而不是set_index, 指定日期时间(类似)列:

data.resample("D", on='created').mean()

但此列仍然必须包含同一时区的所有条目。

关于python - Pandas 重新采样引发由日期时间对象组成的索引的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58032310/

相关文章:

python - 找不到满足 torch>=1.0.0 要求的版本?

python - 如何将 web URL.text 数据转换为 Dataframe

python - python中按距离排序点的奇怪结果

python - 通过外部连接将 Pandas 数据框与列表合并

Python 从 .xls 文件读取数据时出错

python - 在 OpenERP 报表中添加多个对象

python - 使用 python 更改和运行 SQL 查询

python-3.x - 使用 ffmpeg-python 一次读取一个 16 位视频帧

python - 将较短长度的 Numpy 数组连接到 Pandas Dataframe

python - if __name__ == "__main__": 没有额外的缩进