Unexpected behaviour with numpy advanced slicing in named arrays
<p>When using numpy named arrays I observe a different behaviour in the following two cases:</p>

<ol>
<li>case: first using an index array for advanced slicing and then selecting a subarray by name</li>
<li>case: first selecting a subarray by name and then using an index array for advanced slicing</li>
</ol>

<p>The follwing code presents an example</p>

<pre><code>import numpy as np

a = np.ones(5)
data = np.array(zip(a, a, a), dtype=[("x", float), ("y", float), ("z", float)])

# case 1
# does not set elements 1, 3 and 4 of data to 22
data[[1, 3, 4]]["y"] = 22    
print data["y"]  # -&gt; [ 1.  1.  1.  1.  1.]

# case 2
# set elements 1, 3 and 4 of data to 22
data["y"][[1, 3, 4]] = 22
print data["y"]  # -&gt; [  1.  22.   1.  22.  22.]
</code></pre>

<p>The output of the two print commands is 
[ 1.  1.  1.  1.  1.] and [  1.  22.   1.  22.  22.]. Why does changing the order of the selections lead to different results when setting the elements?</p>

<p>Indexing with a list or array <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays" rel="nofollow">always returns a copy rather than a view</a>:</p>

<pre><code>In [1]: np.may_share_memory(data, data[[1, 3, 4]])
Out[1]: False
</code></pre>

<p>Therefore the assignment <code>data[[1, 3, 4]]["y"] = 22</code> is modifying a <em>copy</em> of <code>data[[1, 3, 4]]</code>, and the original values in <code>data</code> will be unaffected.</p>

<p>On the other hand, referencing a field of a structured array <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html#introduction" rel="nofollow">returns a view</a>:</p>

<pre><code>In [2]: np.may_share_memory(data, data["y"])
Out[2]: True
</code></pre>

<p>so assigning to <code>data["y"][[1, 3, 4]]</code> <em>will</em> affect the corresponding elements in <code>data</code>.</p>

python numpy structured-array