python - 遇上TypeError的原因?

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

ticker = [“ZIM”,“ANDE”,“ARKK” ]

stocks = yf.download(ticker, start = “2010-01-01”, end = “2023-01-01”)

ANDE

ANDE.ANDE.resample(“M”).last()


TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_108972\3489082683.py in
----> 1 ande.ANDE.resample(“M”).last()

~\anaconda3\lib\site-packages\pandas\core\series.py in resample(self, rule, axis, closed, label, convention, kind, loffset, base, on, level, origin, offset)
5426 offset: TimedeltaConvertibleTypes | None = None,
5427 ) → Resampler:
→ 5428 return super().resample(
5429 rule=rule,
5430 axis=axis,

~\anaconda3\lib\site-packages\pandas\core\generic.py in resample(self, rule, axis, closed, label, convention, kind, loffset, base, on, level, origin, offset)
8311
8312 axis = self._get_axis_number(axis)
→ 8313 return get_resampler(
8314 self,
8315 freq=rule,

~\anaconda3\lib\site-packages\pandas\core\resample.py in get_resampler(obj, kind, **kwds)
1421 “”"
1422 tg = TimeGrouper(**kwds)
→ 1423 return tg._get_resampler(obj, kind=kind)
1424
1425

~\anaconda3\lib\site-packages\pandas\core\resample.py in _get_resampler(self, obj, kind)
1597 return TimedeltaIndexResampler(obj, groupby=self, axis=self.axis)
1598
→ 1599 raise TypeError(
1600 "Only valid with DatetimeIndex, "
1601 "TimedeltaIndex or PeriodIndex, "

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


但是出現了下面問題, 因此想了解這是什麼原因嗎?

该error是resample所触发的,主要是resample(重采样)的索引需要是datetime格式的,所以只需在resample之前加一行。
data.index = pd.to_datetime(data.index)
参考:http://t.csdn.cn/gaXXY 或者 http://t.csdn.cn/XGyQo

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^