Cornelis
Cornelis

Reputation: 435

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

Upvotes: 1

Views: 294

Answers (2)

Cornelis
Cornelis

Reputation: 435

Just found a solution that might work better:

import scipy.spatial

 
scipy.spatial.distance.cdist(XA, XB, metric='euclidean', *, out=None, **kwargs)

Source:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist

Upvotes: 0

Michael Delgado
Michael Delgado

Reputation: 15432

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()
)

Upvotes: 1

Related Questions