首页 > 解决方案 > TypeError:Pandas iloc 函数返回此错误

问题描述

我试图学习一些基本的交易指标并复制这个脚本:

import yfinance as yf
import matplotlib.pyplot as plt

stock = 'TSLA'
start = '2020-11-01'

df = yf.download(stock , start=start)


def MACD(df):
    df['EMA12'] = df.Close.ewm(span=12).mean()
    df['EMA26'] = df.Close.ewm(span=26).mean()
    df['MACD'] = df.EMA12 - df.EMA26
    df['signal'] = df.MACD.ewm(span=9).mean()
    print('indicators added')
    

MACD(df)

plt.plot(df.signal, label='signal', color='red')
plt.plot(df.MACD, label='MACD', color='green')
plt.legend()
plt.show()

Buy, Sell = [], []

for i in range(2, len(df)):
    if df.MACD.iloc[i] > df.signal.iloc[i] and df.MACD.iloc[i-1] < df.signal.loc[i-1]:
        Buy.append(i)
    elif df.MACD.iloc[i] < df.signal.iloc[i] and df.MACD.iloc[i-1] > df.signal.iloc[i-1]:
        Sell.append(i)

当我尝试调用 Buy 或 Sell 列表时,我收到此错误返回:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-140f9fd1549f> in <module>
     26 
     27 for i in range(2, len(df)):
---> 28     if df.MACD.iloc[i] > df.signal.iloc[i] and df.MACD.iloc[i-1] < df.signal.loc[i-1]:
     29         Buy.append(i)
     30     elif df.MACD.iloc[i] < df.signal.iloc[i] and df.MACD.iloc[i-1] > df.signal.iloc[i-1]:

~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1765 
   1766             maybe_callable = com.apply_if_callable(key, self.obj)
-> 1767             return self._getitem_axis(maybe_callable, axis=axis)
   1768 
   1769     def _is_scalar_access(self, key: Tuple):

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1961 
   1962         # fall thru to straight lookup
-> 1963         self._validate_key(key, axis)
   1964         return self._get_label(key, axis=axis)
   1965 

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
   1828 
   1829         if not is_list_like_indexer(key):
-> 1830             self._convert_scalar_indexer(key, axis)
   1831 
   1832     def _is_scalar_access(self, key: Tuple) -> bool:

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _convert_scalar_indexer(self, key, axis)
    738         ax = self.obj._get_axis(min(axis, self.ndim - 1))
    739         # a scalar
--> 740         return ax._convert_scalar_indexer(key, kind=self.name)
    741 
    742     def _convert_slice_indexer(self, key: slice, axis: int):

~\anaconda3\lib\site-packages\pandas\core\indexes\datetimelike.py in _convert_scalar_indexer(self, key, kind)
    384             is_flt = is_float(key)
    385             if kind in ["loc"] and (is_int or is_flt):
--> 386                 self._invalid_indexer("index", key)
    387             elif kind in ["ix", "getitem"] and is_flt:
    388                 self._invalid_indexer("index", key)

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in _invalid_indexer(self, form, key)
   3075         """
   3076         raise TypeError(
-> 3077             f"cannot do {form} indexing on {type(self)} with these "
   3078             f"indexers [{key}] of {type(key)}"
   3079         )

TypeError: cannot do index indexing on <class 'pandas.core.indexes.datetimes.DatetimeIndex'> with these indexers [1] of <class 'int'>

有人可以给我一个提示,这个错误实际上意味着什么?

我的意思是我得到了代码,但无法理解那个错误。

为什么不能索引?或者在列表中写入更多内容?

标签: pandasdataframefor-loopindexingtypeerror

解决方案


推荐阅读