Numpy 2D array indexing without out of bound and with clipping value
<p>I have indices array </p>

<pre><code>a = np.array([
   [0, 0],
   [1, 1],
   [1, 9]
])
</code></pre>

<p>And 2D array</p>

<pre><code>b = np.array([
   [0, 1, 2, 3],
   [5, 6, 7, 8]
])
</code></pre>

<p>I can do this one</p>

<pre><code>b[a[:, 0], a[:, 1]]
</code></pre>

<p>But it'll be an exception '<strong>out of bounds</strong>', because 9 is out of range. 
I need a <em>very fast way</em> to make array slice by indices and it will be ideal if I can set a clip value, e.g.:</p>

<pre><code>np.indexing_with_clipping(array=b, indices=a, clipping_value=0)
&gt; array([0, 6, --&gt; 0 = clipped value &lt;--])
</code></pre>

<p>You can use list comprehension:</p>

<pre><code>b[
    [min(x,len(b[0])-1) for x in a[:,0]],
    [min(x,len(b[1])-1) for x in a[:,1]]
]
</code></pre>

<p><strong>edit</strong> I used last array value as your clipping value, but you can replace the <code>min()</code> function with whatever you want (e.g. trenary operator)</p>

<p><strong>edit2</strong> OK, based on clarification in comments and all python-fu that I could put together, this snipped finally does what you need:</p>

<pre><code>clipping_value = -1
tmp=np.append(b,[[clipping_value],[clipping_value]],axis=1)
tmp[zip(*[((x,y) if (x&lt;b.shape[0] and y&lt;b.shape[1]) else (0,b.shape[1])) for (x,y) in zip(a.transpose()[0],a.transpose()[1])])]
</code></pre>

<p>It is the same as above, just creates ndarray <code>tmp</code>, which is a copy of <code>b</code> but contains the <code>clipping_value</code> as its last element and then uses my previous solution to set indices so, that they point to the last element if either of the indices is bigger than dimensions of <code>b</code>.</p>

<p>I learned that there is reverse to the <code>zip</code> function and that the numpy arrays accept lists as indices. It was fun. Thanks.</p>

python arrays numpy multidimensional-array