Reputation: 35
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?
Upvotes: 0
Views: 95
Reputation: 120391
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")
Upvotes: 1