简体   繁体   English

使用 numpy 对数组进行排序以适合另一个数组

[英]sort an array to fit another array with numpy

There is a number of questions out here concerning sorting arrays but I was not able to find the one solving my problem (which makes me hope that I'm not thinking way to complicated).这里有很多关于排序数组的问题,但我找不到解决我的问题的问题(这让我希望我没有想复杂的方法)。 So here we go:所以我们开始:

I have two arrays with equal values but in different order:我有两个值相等但顺序不同的数组:

a = np.array([4, 2, 5, 6])
# b = np.random.permutation(a)  # general case
b = np.array([5, 2, 6, 4])

I need the indices that sort b to a, so here:我需要将 b 排序为 a 的索引,所以在这里:

ind = np.array([3, 1, 0, 2])

Note that I do not want to change a.请注意,我不想更改 a。

One approach with broadcasting & np.where - 有一种方法broadcastingnp.where -

_,C = np.where(a[:,None] == b)

Sample run - 样品运行-

In [210]: a = np.array([4, 2, 5, 6])

In [211]: b = np.array([5, 2, 6, 4])

In [212]: _,C = np.where(a[:,None] == b)

In [213]: C
Out[213]: array([3, 1, 0, 2], dtype=int64)

In this case, a is already sorted. 在这种情况下, a已被排序。 So, all you need are the sorting indices for b. 因此,您所需要做的就是b的排序索引。

However, in case a was not sorted, you can do 但是,如果未对a进行排序,则可以执行

a = array([2, 4, 5, 6])
b = array([5, 2, 6, 4])
b.argsort()[a.argsort()] # array([1, 3, 0, 2])

This uses the argsort method to return the indices needed to sort b and a . 这使用argsort方法返回对ba进行排序所需的索引。

Another example: 另一个例子:

a = array([4, 2, 5, 6])
b = array([5, 2, 6, 4])
b.argsort()[a.argsort()] # array([3, 1, 0, 2])

np.argsort is its own inverse. np.argsort是它自己的逆。 If y = x[x.argsort()] , then x = y[x.argsort().argsort()] .如果y = x[x.argsort()] ,则x = y[x.argsort().argsort()] Specifically, you convert a into a sorted array with a.argsort() , and convert from a sorted array to b with b.argsort().argsort() .具体来说,您使用a.argsort()a转换为排序数组,并使用b.argsort().argsort()将排序数组转换为b You can therefore write:因此,您可以编写:

b = a[a.argsort()][b.argsort().argsort()]

In other words:换句话说:

ind = a.argsort()[b.argsort().argsort()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM