假設我們有一些 numpy 陣列A = [1, 2, 2, 3]及其唯一陣列B = [1, 2, 3],其中陣列 B 基本上是陣列 A 的集合。
我希望得到一個新陣列C = [0, 1, 1, 2],它是陣列 A,但其元素交換為陣列 B 中匹配元素的索引。
我將如何實作這一目標?
注意:我的陣列 A 和 B 分別包含 18m 和 138k 值,因此解決方案必須有效。
uj5u.com熱心網友回復:
使用numpy.where:
A = np.array([1, 2, 2, 3])
B = np.array([1, 2, 3])
C = np.where(A==B[:,None])[0]
輸出: array([0, 1, 1, 2])
uj5u.com熱心網友回復:
用:
import numpy as np
A = np.array([1, 2, 2, 3])
B = np.array([1, 2, 3])
res = (A[:, None] == B).argmax(1)
print(res)
輸出
[0 1 1 2]
選擇:
_, res = (A[:, None] == B).nonzero()
print(res)
輸出
[0 1 1 2]
替代方案,應該使用更少的記憶體:
import numpy as np
A = np.array([1, 2, 2, 3])
B = np.array([1, 2, 3])
# find the uniques values together with the inverse
Bp, inverse = np.unique(A, return_inverse=True)
# find the indices mapping Bp to B
indices = (Bp[:, None] == B).argmax(1)
# index on the mapping
result = indices[inverse]
print(result)
輸出
[0 1 1 2]
如果B是總是一個獨特排序的元素,你可以直接做:
import numpy as np
A = np.array([1, 2, 2, 3])
B = np.array([1, 2, 3])
# find the uniques values together with the inverse
_, inverse = np.unique(A, return_inverse=True)
print(inverse)
輸出
[0 1 1 2]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/316991.html
