Ashleigh Clayton
Ashleigh Clayton

Reputation: 1445

Simple for loop in pandas

I have a simple indexing question with respect to pandas. I would like to make a simple for loop to go over numbers 1 to 5. I'm having trouble with pandas indexing in how to do this (although I'm sure its simple!)

My rough code:

def averaged_rel_track(current_tracks, rel_values):

    current_tracks['rel_values']=rel_values
    current_tracks=current_tracks.set_index('candidate')

    #I would like this line to loop over numbers 1 to 5
    b_1= current_tracks.rel_values.loc['1']

What I have tried:

for i in range(1, 6):
    b=current_tracks.rel_values.iloc[i]

for i in range (1, 6):
    b = current_tracks.rel_values[i]

for i in range (1, 6):
   b=current_tracks.rel_values['i']

and various other similar variations (including .ix, .iloc, .loc)

Upvotes: 1

Views: 22534

Answers (1)

hans_meine
hans_meine

Reputation: 1921

Your first try does not look too bad; I think you could use:

for i in range(5):
    b = current_tracks.rel_values.iloc[i] # by standard 0-based sequence index

or

for i in range(1, 6):
    b = current_tracks.rel_values.loc[i] # by 1-based track number

But you probably want to avoid 'for i in range(...)', which is not pythonic:

for b in current_tracks.rel_values.loc[1:5]: # or .iloc[:5]
    ...

Note that .loc[1:5] includes the last index value, while .iloc does not. That's more intuitive than it sounds, since .iloc uses standard python indexing, while .loc supports any kind of application-specific indices, and it might not be possible to "increment" the end index in non-integer cases.

Upvotes: 3

Related Questions