這裏有兩個numpy
選項np.in1d
這是從基礎python in
矢量化版本。當陣列是大的,第一個選項顯示了一些加速:
選項一個(快速一個):
np.in1d(A, L).reshape(A.shape).astype(int)
選擇二(慢一個):
np.apply_along_axis(np.in1d, 0, A, L).astype(int)
計時:
A = np.random.randint(0, 10, (1000, 1000))
L = [3,4,5]
def loop():
B = np.zeros(A.shape)
for e in L:
B[A==e] = 1
return B
%timeit np.in1d(A, L).reshape(A.shape).astype(int)
# 100 loops, best of 3: 6.4 ms per loop
%timeit loop()
# 100 loops, best of 3: 16.8 ms per loop
%timeit np.apply_along_axis(np.in1d, 1, A, L).astype(int)
# 10 loops, best of 3: 21.5 ms per loop
%timeit np.apply_along_axis(np.in1d, 0, A, L).astype(int)
# 10 loops, best of 3: 35.1 ms per loop
結果檢查:
B1 = loop()
B2 = np.apply_along_axis(np.in1d, 0, A, L).astype(int)
B3 = np.apply_along_axis(np.in1d, 1, A, L).astype(int)
B4 = np.in1d(A, arrL).reshape(A.shape).astype(int)
(B1 == B2).all()
# True
(B1 == B3).all()
# True
(B1 == B4).all()
# True
我時序結果提供了不同的敘事。我在anaconda中使用python 3.5和numpy 1.10.4,原始循環大約比使用in1d快3倍。編輯:我現在看到你使用了一個1000x1000的隨機矩陣。我將用相同大小的矩陣進行重新測試。 –
@ HAL9001我剛剛測試了python 3,我得到了相當一致的結果。第一個np.in1d選項更快。你正在測試的陣列有多大? – Psidom
Psidom的結果在使用1000x1000時得到確認。 –