'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 ?

import math
import xarray as xr 
import numpy as np

#set the specified lat, lon
specific_lat = 15
specific_lon = 65

#create sample xarry data
lat = [0, 10, 20]
lon = [50, 60, 70, 80]

#sample data
test_data = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

#to xarray
data_xarray = xr.DataArray(test_data, dims=("lat","lon"), coords={"lat":lat, "lon":lon})

#calculate distance
xarray_distance = data_xarray #copy
xarray_distance.data[:,:] = 0.0 #zero-reset

for lat in data_xarray.lat.data:
    for lon in data_xarray.lon.data:
        xarray_distance.loc[{"lat":lat,"lon":lon}] = math.sqrt((lat- spec_lat)**2 + (lon - spec_lon)**2)

print(xarray_distance)

#<xarray.DataArray (lat: 3, lon: 4)>
#array([[21, 15, 15, 21],
#       [15,  7,  7, 15],
#       [15,  7,  7, 15]])
#Coordinates:
#  * lat      (lat) int64 0 10 20
#  * lon      (lon) int64 50 60 70 80



Solution 1:[1]

You need to calculate Cosine weighting by: (lon - spec_lon)**2 and that is equal to (cos(lat)*(lon - spec_lon))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 General Grievance