Is there an efficient way to update each individual row in a DataFrame with values from the row below it in sequence?
The DataFrame contains a sequence of positions to which a vehicle travelled in order. I've added two new columns next_x
and next_y
, and want to populate those columns, by row, with the values in the current_x
and current_y
column from the row directly beneath. The idea being each row will then contain pairs of coordinates describing a position, and the next position a vehicle travelled.
This is working using iterrows
but is prohibitively slow over the full dataset.
for index, row in df.iterrows():
if int(index) < len(df)-1:
df['next_x'].iloc[int(index)] = df['current_x'].iloc[(int(index)+1)]
df['next_y'].iloc[int(index)] = df['current_y'].iloc[(int(index)+1)]
I can't figure out a good way to use apply
- am I missing something?