Numpy: sort array rows by rows in another array

I have a 2D array of "neighbors" and I want to reorder each row according to the corresponding row in another matrix (the so-called "radii"). The code is below, but it uses a loop forfor the numpy array, which, as I know, is the wrong way. What is the right solution to change the number / broadcast for this reordering?

neighbors = np.array([[8,7,6], [3,2,1]])
radii = np.array([[0.4, 0.2, 0.1], [0.3, 0.9, 0.1]])

order = radii.argsort(axis=1)
for i in range(2):
    neighbors[i] = neighbors[i,order[i]]
print(neighbors)

# Result:
[[6 7 8]
 [1 3 2]]
+4
source share
1 answer

In NumPy you should write something like this:

>>> neighbors[np.arange(2)[:, None], order]
array([[6, 7, 8],
       [1, 3, 2]])

(More generally, you instead write the first index as np.arange(order.shape[0])[:, None].)

, np.arange(2)[:, None] :

array([[0],
       [1]])

:

array([[2, 1, 0],
       [2, 0, 1]])

NumPy , . [0] [2, 1, 0], , . [1] [2, 0, 1] .

+2

Source: https://habr.com/ru/post/1625652/


All Articles