import numpy as np
a = np.array([[[9, 8, 8],
[4, 9, 1]],
[[6, 6, 3],
[9, 3, 5]]])
ind=(a[:,:,1]<=8) & (a[:,:,1]>=6)
a[ind,1]=a[ind,0]*2
print(a)
產生
[[[ 9 18 8]
[ 4 9 1]]
[[ 6 12 3]
[ 9 3 5]]]
如果你想在一組不是簡單的範圍檢查會員的話,我喜歡用Python的循環都mac's idea和bellamyj's idea使用NP的.in1d。這是更快取決於check_tuple
大小:
test.py:
import numpy as np
np.random.seed(1)
N = 10
a = np.random.randint(1, 1000, (2, 2, 3))
check_tuple = np.random.randint(1, 1000, N)
def using_in1d(a):
idx = np.in1d(a[:,:,1], check_tuple)
idx=idx.reshape(a[:,:,1].shape)
a[idx,1] = a[idx,0] * 2
return a
def using_in(a):
idx = np.zeros(a[:,:,0].shape,dtype=bool)
for n in check_tuple:
idx |= a[:,:,1]==n
a[idx,1] = a[idx,0]*2
return a
assert np.allclose(using_in1d(a),using_in(a))
當N = 10,using_in
稍快:
% python -m timeit -s'import test' 'test.using_in1d(test.a)'
10000 loops, best of 3: 156 usec per loop
% python -m timeit -s'import test' 'test.using_in(test.a)'
10000 loops, best of 3: 143 usec per loop
當N = 100時,using_in1d
要快得多:
% python -m timeit -s'import test' 'test.using_in1d(test.a)'
10000 loops, best of 3: 171 usec per loop
% python -m timeit -s'import test' 'test.using_in(test.a)'
1000 loops, best of 3: 1.15 msec per loop
是否有官方numpy的-輔導徽章?如果是的話,你會得到它。:)你有沒有指向在numpy上的一些很好的研究材料?官方的[暫定]教程和參考資料的構成方式使我很難找到我需要的信息......: -/ – mac
順便說一句:這是一個整潔的解決方法,但如果可以使用'in'運算符會更喜歡,因爲在我的「真實情況」中,我有大約10個值的池,不僅是'(6,8)'。 – mac
訣竅不在於你閱讀的內容,而在於你如何閱讀它。對於每個功能,花幾分鐘時間詢問一下, 演示該功能如何運行的簡單示例是什麼?我什麼時候可以用這個?開始構建 一個演示/演示每個功能/概念的示例文件。學習是構建示例文件的副作用。 暫定教程和官方文檔是很好的資源。您可能還會嘗試在[numpy book](http://www.tramy.us/)和 [用戶指南](http://docs.scipy.org/doc/numpy/numpy- user.pdf)。 祝你好運! – unutbu