Numpy Lookup(地图或点) [英] Numpy Lookup (Map, or Point)
问题描述
我有一个大的numpy数组:
I have a large numpy array:
array([[32, 32, 99, 9, 45], # A
[99, 45, 9, 45, 32],
[45, 45, 99, 99, 32],
[ 9, 9, 32, 45, 99]])
以及特定订单中的大量唯一值数组:
and a large-ish array of unique values in a particular order:
array([ 99, 32, 45, 9]) # B
我怎样才能快速(没有python词典,没有 A
的副本,没有python循环)替换 A
以便成为 B
中值的指示?:
How can I quickly (no python dictionaries, no copies of A
, no python loops) replace the values in A
so that become the indicies of the values in B
?:
array([[1, 1, 0, 3, 2],
[0, 2, 3, 2, 1],
[2, 2, 0, 0, 1],
[3, 3, 1, 2, 0]])
我感到非常愚蠢,因为我无法做到这一点,也没有在文档中找到它。简单点!
推荐答案
在这里你去了
A = array([[32, 32, 99, 9, 45], # A
[99, 45, 9, 45, 32],
[45, 45, 99, 99, 32],
[ 9, 9, 32, 45, 99]])
B = array([ 99, 32, 45, 9])
ii = np.argsort(B)
C = np.digitize(A.reshape(-1,),np.sort(B)) - 1
最初我建议:
D = np.choose(C,ii).reshape(A.shape)
但我意识到当你去更大的数组时有限制。相反,借用@ unutbu的聪明回复:
But I realized that that had limitations when you went to larger arrays. Instead, borrowing from @unutbu's clever reply:
D = np.argsort(B)[C].reshape(A.shape)
或单行
np.argsort(B)[np.digitize(A.reshape(-1,),np.sort(B)) - 1].reshape(A.shape)
我发现它比@ unutbu的代码更快或更慢,具体取决于所考虑的数组的大小和数量独特的价值观。
Which I found to be faster or slower than @unutbu's code depending on the size of the arrays under consideration and the number of unique values.
这篇关于Numpy Lookup(地图或点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!