Search code examples
pythonpandasgeolocation

Relative distance to previous row, in pandas/python


I have a dataframe with a series of locations in it. The three columns i have so far are:

['Location number','x_coordinate', 'y_coordinate]

Now i would like to have a forth column which indicates the distance. between te previous one.

As the firts location does not has a preceding location, i't distance can just be zero.

For the other location, 'manhattan distance' should be most easy to compute, and is just perfect for my use.

For those not familiar to the manhattan distance: delta x + delta y


Solution

  • The pd.Series.diff method should do the trick:

    df['manhattan_distance'] = (
        df.x_coordinate.diff().fillna(0).abs()
        + df.y_coordinate.diff().fillna(0).abs()
    )