我正在尝试对一个非常简单的数据帧进行重新采样,但失败并出现以下异常:
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'
最佳答案
让我们从一些原则开始:
要进行重新采样,源Series或DataFrame必须具有例如 DatetimeIndex(不是“普通”索引)。
您可以为该列设置索引,但为此,所有日期时间 元素必须位于相同时区(您的数据不是)。
因此您可以按照以下步骤操作:
将创建的列转换为日期时间(代码的一部分)时, 传递utc=True来“统一”时区:
data.created = pd.to_datetime(data.created, utc=True)
设置索引,然后您可以自由地重新采样:
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/