在中调用resample()时出现TypeError

2024-09-30 20:34:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经有一段时间没有接触代码了,直到我的整个代码块开始让我头痛好几天了。它以前一直工作到resample的挑战出现。你知道吗

错误如下:

File "C:\Users\JonesDavid\Local\Programs\Python\Python35\lib\site-packages\pandas\core\generic.py", line 5522, in resample base=base, key=on, level=level)

File "C:\Users\JonesDavid\Local\Programs\Python\Python35\lib\site-packages\pandas\core\resample.py", line 999, in resample return tg._get_resampler(obj, kind=kind)

File "C:\Users\JonesDavid\Local\Programs\Python\Python35\lib\site-packages\pandas\core\resample.py", line 1116, 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'

  • 在doForecast中:tsWeekly = ts.resample('W-MON').last())
  • 主要内容:doForecast(panel)
  • 在:main()

这是我的全部代码减去绘图相关部分:

import pandas_datareader.data as web
from datetime import datetime
# removed imports related to plotting

TRAIN_SIZE = 0.2
FORECAST_STEPS = 20
STOCKS_PREDICT = ['SPY', 'AAPL']


def downloadData(startDate, endDate):

    histPanel = web.DataReader(STOCKS_PREDICT, 'iex' , startDate, endDate)
    contains_condition = ((histPanel.isnull()) | (histPanel == 0)).any(axis=1)
    to_keep = contains_condition[contains_condition == False].index
    histPanel = histPanel.loc[to_keep]

    return histPanel


print(downloadData("01/01/2017","01/01/2019"))


def doForecast(Panel):

    closeDF = Panel['close']
    ts = closeDF['SPY']
    tsWeekly = ts.resample('W-MON').last() # TypeError here
    values = tsWeekly.tolist()

    # removed unrelevant plotting code


def main():
    startDate = datetime(2017, 1, 1)
    endDate = datetime.today()

    panel = downloadData(startDate, endDate)

    doForecast(panel)


if __name__ == '__main__':
    main()

Tags: 代码pandasdatetimemainlocalusersfileresample