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]]]
Если вы хотите проверить членство в наборе, который не является простым диапазоном, тогда мне нравится идея обоих mac об использованиицикл Python и идея Белламия об использовании 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