[英]Numpy: sort rows of an array by rows in another array
I have a 2D array of "neighbors", and I want to re-order each row according to a corresponding row in another matrix (called "radii"). 我有一个“邻居”的2D数组,我想根据另一个矩阵(称为“半径”)中的相应行重新排序每一行。 The below code works, but it uses a
for
loop over a numpy array, which I know is the incorrect way to do it. 下面的代码工作,但它在一个numpy数组上使用
for
循环,我知道这是不正确的方法。 What is the correct numpy / broadcast solution to this re-ordering? 这次重新排序的正确numpy /广播解决方案是什么?
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]]
In NumPy you would write something like this: 在NumPy中你会写这样的东西:
>>> neighbors[np.arange(2)[:, None], order]
array([[6, 7, 8],
[1, 3, 2]])
(More generally you'd write the first index as np.arange(order.shape[0])[:, None]
instead.) (更一般地说,您将第一个索引写为
np.arange(order.shape[0])[:, None]
。)
This works because np.arange(2)[:, None]
looks like this: 这是有效的,因为
np.arange(2)[:, None]
看起来像这样:
array([[0],
[1]])
and order looks like this: 和顺序看起来像这样:
array([[2, 1, 0],
[2, 0, 1]])
For the fancy indexing, NumPy pairs off the arrays indexing each axis. 对于花哨的索引,NumPy配对索引每个轴的数组。 The row index
[0]
is paired with the column index [2, 1, 0]
and the new row is created in the order this determines. 行索引
[0]
与列索引[2, 1, 0]
2,1,0 [0]
配对,新行按此确定的顺序创建。 Similarly for [1]
and [2, 0, 1]
to determine the second row. 类似地,
[1]
和[2, 0, 1]
确定第二行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.