Note that there are some explanatory texts on larger screens.

plurals
  1. POReplace subarrays in numpy
    text
    copied!<p>Given an array,</p> <pre><code>&gt;&gt;&gt; n = 2 &gt;&gt;&gt; a = numpy.array([[[1,1,1],[1,2,3],[1,3,4]]]*n) &gt;&gt;&gt; a array([[[1, 1, 1], [1, 2, 3], [1, 3, 4]], [[1, 1, 1], [1, 2, 3], [1, 3, 4]]]) </code></pre> <p>I know that it's possible to replace values in it succinctly like so,</p> <pre><code>&gt;&gt;&gt; a[a==2] = 0 &gt;&gt;&gt; a array([[[1, 1, 1], [1, 0, 3], [1, 3, 4]], [[1, 1, 1], [1, 0, 3], [1, 3, 4]]]) </code></pre> <p>Is it possible to do the same for an entire row (last axis) in the array? I know that <code>a[a==[1,2,3]] = 11</code> will work and replace all the elements of the matching subarrays with 11, but I'd like to substitute a different subarray. My intuition tells me to write the following, but an error results,</p> <pre><code>&gt;&gt;&gt; a[a==[1,2,3]] = [11,22,33] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: array is not broadcastable to correct shape </code></pre> <p>In summary, what I'd like to get is:</p> <pre><code>array([[[1, 1, 1], [11, 22, 33], [1, 3, 4]], [[1, 1, 1], [11, 22, 33], [1, 3, 4]]]) </code></pre> <p>... and n of course is, in general, a lot larger than 2, and the other axes are also larger than 3, so I don't want to loop over them if I don't need to.</p> <hr> <p>Update: The <code>[1,2,3]</code> (or whatever else I'm looking for) is not always at index 1. An example:</p> <pre><code>a = numpy.array([[[1,1,1],[1,2,3],[1,3,4]], [[1,2,3],[1,1,1],[1,3,4]]]) </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