我有一個一維陣列,例如:
a = [1, 3, 4, 7, 9]
然后是另一個二維陣列:
b = [[1, 4, 7, 9], [3, 7, 9, 1]]
我想要第三個具有相同形狀 b 的陣列,其中每個專案是 a 中相應專案的索引,即:
c = [[0, 2, 3, 4], [1, 3, 4, 0]]
使用 numpy 的矢量化方法是什么?
uj5u.com熱心網友回復:
這可能沒有意義,但是......你可以使用 np.interp 來做到這一點......
a = [1, 3, 4, 7, 9]
sorting = np.argsort(a)
positions = np.arange(0,len(a))
xp = np.array(a)[sorting]
fp = positions[sorting]
b = [[1, 4, 7, 9], [3, 7, 9, 1]]
c = np.rint(np.interp(b,xp,fp)) # rint is better than astype(int) because floats are tricky.
# but astype(int) should work faster for small len(a) but not recommended.
只要len(a)小于 float (16,777,217) .... 的最大可表示 int 并且該演算法具有 O(n*log(n)) 速度(或者更確切地說是 len(b)*log(len (a)) 準確地說)
uj5u.com熱心網友回復:
實際上,此解決方案是單行的。唯一的問題是您需要在執行單線之前重新調整陣列的形狀,然后再重新調整它的形狀:
import numpy as np
a = np.array([1, 3, 4, 7, 9])
b = np.array([[1, 4, 7, 9], [3, 7, 9, 1]])
original_shape = b.shape
c = np.where(b.reshape(b.size, 1) == a)[1]
c = c.reshape(original_shape)
結果是:
[[0 2 3 4]
[1 3 4 0]]
uj5u.com熱心網友回復:
廣播救人!
>>> ((np.arange(1, len(a) 1)[:, None, None]) * (a[:, None, None] == b)).sum(axis=0) - 1
array([[0, 2, 3, 4],
[1, 3, 4, 0]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484203.html
