简体   繁体   中英

Cannot resample time series data, TypeError

I am trying to resample this data downloaded from quandl but keep have a TypeError thrown my way even though it looks to be of the datetime64[ns] type.

I have tried running pd.to_datetime(df['Date']) to ensure it of the datetime type with no luck.

df = pd.read_pickle('data1')
print(df.Close.head())
df = df.reset_index()
df = df[['Date', 'Close']]
print(df.Date.head())
df = df.resample('W').mean

Date
2004-08-19    100.335
2004-08-20    108.310
2004-08-23    109.400
2004-08-24    104.870
2004-08-25    106.000
Name: Close, dtype: float64
0   2004-08-19
1   2004-08-20
2   2004-08-23
3   2004-08-24
4   2004-08-25
Name: Date, dtype: datetime64[ns]
Traceback (most recent call last):
  File "/Users/raymond.devries/PycharmProjects/untitled2/datatry.py", line 15, in <module>
    df = df.resample('W').mean
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/generic.py", line 8155, in resample
    base=base, key=on, level=level)
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/site-packages/pandas/core/resample.py", line 1250, in resample
    return tg._get_resampler(obj, kind=kind)
  File "/Users/raymond.devries/PycharmProjects/untitled2/venv/lib/python3.7/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 'RangeIndex'

错误明确指出resample只对日期索引格式有效,另一方面你得到范围索引就像数据帧首先将索引从范围转换为日期类型数据,删除日期列然后重新取样它将起作用。

I did not realize that the date time data times needed to be set as the index. The resample function reads the index of the data frame. The index of data frame was already set to a date time index, therefore I did not need to run df = df.reset_index() and by doing so I turned my index into a range object.

Working code:

df = pd.read_pickle('data1')
df = df[['Close']]
df = df.resample('W').mean()
print(df.head())

Output:

               Close
Date                
2004-08-22  104.3225
2004-08-29  106.8660
2004-09-05  101.2300
2004-09-12  102.8800
2004-09-19  112.4900

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM