0

I keep running into an error that is saying that my index is out of bounds at line (19). However I have added conditions making it so that it couldn't be out of bounds if it followed through with the loop. I am unsure why I keep getting this python error.

Here is a rough version of the code I am using:

df = pd.read_csv('some_csv.csv', sep=" ")
new_list = df.values.tolist()

for i in range(len(new_list[:]) - 1):
  if new_list[i][2] == new_list[i+1][2]:
      do some property
  else:
      do something different

However I keep encountering the error:

Traceback (most recent call last):
 File "PVE.py", line 18
    if new_list[I][2] == new_list[I+1][2]
IndexError: list index out of range

I shouldn't be out of range, since I am telling it to be literally -1 off the top of the range, to account for the +1 it is comparing it to. Why am I encountering this error? How can I fix this?

  • Did you consider the possibility that the `[2]` is the "out-of-range" index rather than `i+1`? Also, did you consider [looking for a more elegant way to do this](https://stackoverflow.com/questions/5434891) ([or](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator))? Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and https://stackoverflow.com/help/minimal-reproducible-example. – Karl Knechtel Mar 10 '22 at 19:27
  • Yup that was it. When loading it into the df to a list, it made it non-indexable. i.e it went from the pandas dataframe into a list of strings rather than a list of lists. Thank you – Confused_scientist Mar 10 '22 at 19:32
  • You probably have only 2 columns in your dataframe, so the third index (2) is out of range. – Corralien Mar 10 '22 at 19:33

1 Answers1

1

As I said in my comment, you have only 2 columns in your dataframe, so the third index ([2]) is out of range.

You can use this code which is equivalent to your loop:

import numpy as np

np.where(df['col2'] == df['col2'].shift(-1), "do some property", "do something different")
Corralien
  • 109,409
  • 8
  • 28
  • 52