1
$\begingroup$

Encountred an index error when trying to run the code found here: https://github.com/snazrul1/PyRevolution/blob/master/Puzzles/DSP_For_Stock_Prices.ipynb

The error occurs in section In[10]:

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

Error message:

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

I have the latest versions of numpy and pandas installed, and using Python 3.6

$\endgroup$
0
$\begingroup$

In that section, within the for-loop, n is an integer (you loop over a range().

If you use the square brackets to access the Pandas DataFrame (or a Series, in this case), you are trying to access the index of the table. In this case, the index is a timestamp - have a look at the df in section Out [7].

So you need to get values by timestamp, or to use the row number itself, you must do as Vaalizaadeh said in a comment and use the .iloc accessor to the pandas object.

So just change shift = dominantTheta[n] to this: shift = dominantTheta.iloc[n].

$\endgroup$
  • $\begingroup$ Problem solved - thank you! $\endgroup$ – Kyle Jun 28 at 7:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.