Iterating A Pandas Dataframe Over 'n' Next Rows
I have this Pandas dataframe df: station a_d direction a 0 0 a 0 0 a 1 0 a 0 0 a 1 0 b 0 0 b 1 0
Solution 1:
You are not effectively using z
in the inner for loop. You never access the i+z
-th row. You access the i-th row and the i+1
-th row and the i+2
-th row, but never the i+z
-th row.
You can replace that inner for loop with:
if i+1 > len(df)-1:
pass
elif (df.loc[i+1,'a_d'] == df.loc [i,'a_d']):
pass
elif (df.loc [i+2,'station'] == df.loc [i,'station'] and (df.loc [i+2,'direction'] == df.loc [i,'direction'])):
pass
else:
df.loc[i,'value_id'] = value_id
Note that I also slightly optimized the second elif
because at that point you already know df.loc[i+1,'a_d']
does not equal df.loc [i,'a_d']
.
Not having to loop over z
will save a lot of time.
Post a Comment for "Iterating A Pandas Dataframe Over 'n' Next Rows"