Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>import numpy as np a = np.array([[[9, 8, 8], [4, 9, 1]], [[6, 6, 3], [9, 3, 5]]]) ind=(a[:,:,1]&lt;=8) &amp; (a[:,:,1]&gt;=6) a[ind,1]=a[ind,0]*2 print(a) </code></pre> <p>yields</p> <pre><code>[[[ 9 18 8] [ 4 9 1]] [[ 6 12 3] [ 9 3 5]]] </code></pre> <hr> <p>If you wish to check for membership in a set which is not a simple range, then I like both <a href="https://stackoverflow.com/questions/8024305/numpy-checking-if-an-element-in-a-multidimensional-array-is-in-a-tuple/8024538#8024538">mac's idea</a> of using a Python loop and <a href="https://stackoverflow.com/questions/8024305/numpy-checking-if-an-element-in-a-multidimensional-array-is-in-a-tuple/8024510#8024510">bellamyj's idea</a> of using np.in1d. Which is faster depends on the size of <code>check_tuple</code>:</p> <p><strong>test.py:</strong></p> <pre><code>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)) </code></pre> <p>When N = 10, <code>using_in</code> is slightly faster:</p> <pre><code>% 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 </code></pre> <p>When N = 100, <code>using_in1d</code> is much faster:</p> <pre><code>% 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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload