Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading