Skip to content
Advertisement

How to calculate the euclidian distance between a specified coordinate and 2-d xarray data at once

How to calculate the euclidian distance between a specified coordinate and 2-d xarray data at once (without for loop)?

I wrote the following code. But if the data-size become larger, this script appears to be slow. How can I do the same thing without for loop ?

JavaScript

Advertisement

Answer

First things first, xarray_distance = data_xarray does not copy the object. Both names will see the same object and any changes that occur to it equally. For a copy, you want to do data_xarray.copy().

Now, instead of using loops, you want to take advantage of numpy’s vectorisation and broadcasting to create the 2D array in one go and set that to your xarray’s object data.

JavaScript

Result

JavaScript

You’ll notice the data are floats, as they should probably be, considering what they represent. If you want them in the original type of the data, substitute

JavaScript

with

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement