Paz Bar-Tal
Paz Bar-Tal

Reputation: 1

KeyError when accessing Pandas data Frame in a For loop

I am working with a Pandas dataFrame of an experiment that describes hand and head coordinates in VR (just_trials). In each trial, a virtual environment appears, then a black screen, and then again a virtual environment.

I have a column that describes the trial number ("staircaseCounterIndex", and another column that describes what the subject sees: a room or a black screen ("SceneName").

For example:

Dataset's columns

Because the data set shows me millisecond coordinates of motion, the values ​​in SceneName, and in staircaseCounterIndex do not change as long as the scene has not changed or the trial is over, respectively. I want to add a new column to the data set that will count me the times the subject has seen the room (i.e. after a room has appeared when previously there was a black screen will add +1 to the count).

Below is the code:

step_index = []
first_step = -2  
step_num = 0

for i in range(2, np.shape(just_trials)[0]):
    print(i)
    if (first_step == just_trials['staircaseCounterIndex'][i]) and (just_trials['SceneName'][i] == 'Room'): # and just_trials['SceneName'][i-1] == 'Room': ## **Here is the error** ##
        step_index.append(step_num)
    elif just_trials['SceneName'][i] == 'BlackScreen':
        step_index.append(0)
    else:
        step_num += 1
        first_step = just_trials['staircaseCounterIndex'][i]
        step_index.append(step_num)

My problem is that when I try to run the code pycharm encounters an error in the third iteration of the For loop:

the line where the error occurs is marked in the code above.

Error message

But when I run the debugger, everything works just fine.

Would be thankful for your help, Paz.

Upvotes: 0

Views: 643

Answers (1)

Franco Piccolo
Franco Piccolo

Reputation: 7410

Try with .iloc for indexing.

just_trials['staircaseCounterIndex'].iloc[i]

Upvotes: 2

Related Questions