以另一个顺序排列一个numpy数组 [英] Order one numpy array by another
问题描述
我有一个确定元素顺序的数组:
I have an array that determines an ordering of elements:
order = [3, 1, 4, 2]
然后我想对另一个更大的数组(仅包含那些元素)进行排序:
And then I want to sort another, larger array (containing only those elements):
a = np.array([4, 2, 1, 1, 4, 3, 1, 3])
,使得order
中最先出现的元素在结果中排名第一,等等.
在直接的Python中,我可以通过一个关键函数来做到这一点:
such that the element(s) that come first in order
come first in the results, etc.
In straight Python, I would do this with a key function:
sorted(a, key=order.index)
[3, 3, 1, 1, 1, 4, 4, 2]
我怎样才能用numpy做到这一点? numpy数组是否有类似的键函数"概念?
How can I do this (efficiently) with numpy? Is there a similar notion of "key function" for numpy arrays?
推荐答案
特定情况:Ints
对于ints
,我们可以使用 bincount
-
Specific case : Ints
For ints
, we could use bincount
-
np.repeat(order,np.bincount(a)[order])
样品运行-
In [146]: sorted(a, key=order.index)
Out[146]: [3, 3, 1, 1, 1, 4, 4, 2]
In [147]: np.repeat(order,np.bincount(a)[order])
Out[147]: array([3, 3, 1, 1, 1, 4, 4, 2])
一般情况
方法1
使用bincount
-
# https://stackoverflow.com/a/41242285/ @Andras Deak
def argsort_unique(idx):
n = idx.size
sidx = np.empty(n,dtype=int)
sidx[idx] = np.arange(n)
return sidx
sidx = np.argsort(order)
c = np.bincount(np.searchsorted(order,a,sorter=sidx))
out = np.repeat(order, c[argsort_unique(sidx)])
方法#2-A
对于order
中的所有元素都在a
-
With np.unique
and searchsorted
for the case when all elements from order
are in a
-
unq, count = np.unique(a, return_counts=True)
out = np.repeat(order, count[np.searchsorted(unq, order)])
方法#2-B
要涵盖所有情况,我们需要再执行一步-
To cover for all cases, we need one extra step -
unq, count = np.unique(a, return_counts=1)
sidx = np.searchsorted(unq, order)
out = np.repeat(order, np.where(unq[sidx] == order,count[sidx],0))
这篇关于以另一个顺序排列一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!