array([[-0.06366486, -2.43028317],
[ 2.01224776, -0.66531383],
[ 0.77307079, -0.29340495],
[ 0.39044409, 0.85686349],
[-0.92426404, 0.34792792],
[-0.94323693, 0.69295404],
[-1.34289803, -1.18248516],
[-1.19844352, -1.27501523],
[-0.82092882, -0.76365567],
[ 0.44943198, -1.0941035 ]])
I have array given above , I want to arrange this array points in ascending according to Euclidean distance from origin.
CodePudding user response:
distances to origin can be calculated using np.linalg.norm
, then by achieving the ordering (sort_), the main coordinates arr can be sorted based on the distances:
to_dist = np.array([0.0, 0.0])
dist = np.linalg.norm(arr - to_dist, axis=1)
# [2.4311169245398436 2.1193828205433505 0.8268765996421271
# 0.9416271172342628 0.9875818209913788 1.1704192444026826
# 1.7893144700130568 1.7498373374008063 1.121202082512221
# 1.1828151053140006]
sort_ = np.argsort(dist)
# [2 3 4 8 5 9 7 6 1 0]
res = arr[sort_]
# [[ 0.77307079 -0.29340495]
# [ 0.39044409 0.85686349]
# [-0.92426404 0.34792792]
# [-0.82092882 -0.76365567]
# [-0.94323693 0.69295404]
# [ 0.44943198 -1.0941035 ]
# [-1.19844352 -1.27501523]
# [-1.34289803 -1.18248516]
# [ 2.01224776 -0.66531383]
# [-0.06366486 -2.43028317]]
CodePudding user response:
import numpy as np
arr= np.array(define your 2 dimension al array here)
print(np.sort(arr))
hope this code surely works
Plz reply after using this