Python熊猫索引错误

数据挖掘 机器学习 Python 熊猫
2022-02-14 21:09:26

尝试运行此处找到的代码时遇到索引错误。 错误发生在 In[10] 部分:

for n in range(len(dominantTheta)):
    shift = dominantTheta[n]
    regressionDelta += dominantAmp[n] * np.cos(n * np.array(range(len(df))) + shift)

错误信息:

Traceback (most recent call last):
  File "C:/Users/xxx/Desktop/Python Workspace/DSP.py", line 62, in <module>
    shift = dominantTheta[n]
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\series.py", line 868, in __getitem__
    result = self.index.get_value(self, key)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\indexes\base.py", line 4375, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas\_libs\index.pyx", line 81, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 89, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 0

我安装了最新版本的 numpy 和 pandas,并使用 Python 3.6

1个回答

在该部分中,在 for 循环中,n是一个整数(您在range().

如果您使用方括号来访问 Pandas DataFrame(或系列,在这种情况下),您正在尝试访问表的索引在这种情况下,索引是一个时间戳 - 看看dfin 部分Out [7]

因此,您需要按时间戳获取值,或者要使用行号本身,您必须按照 Vaalizaadeh 在评论中所说的那样做,并使用.ilocpandas 对象的访问器。

所以只需更改shift = dominantTheta[n]为:shift = dominantTheta.iloc[n].