Python numpy array integer indexed flat slice assignment
<p>Was experimenting with numpy and found this strange behavior.
This code works ok:</p>

<pre><code>&gt;&gt;&gt; a = np.array([[1, 2, 3], [4, 5, 6]])    
&gt;&gt;&gt; a[:, 1].flat[:] = np.array([-1, -1])
&gt;&gt;&gt; a 
array([[ 1, -1,  3],
       [ 4, -1,  6]])
</code></pre>

<p>But why this code doesn't change to -1 elements of 0 and 2 column?</p>

<pre><code>&gt;&gt;&gt; a[:, [0, 2]].flat[:] = np.array([-1, -1])
&gt;&gt;&gt; a 
array([[ 1, -1,  3],
       [ 4, -1,  6]])
</code></pre>

<p>And how to write the code so that would change to -1 elements of 0 and 2 columns like this?</p>

<p>UPD: use of <code>flat</code> or smt similar is necessarily in my example</p>

<p>UPD2: I made example in question basing on this code:</p>

<pre><code>img = imread(img_name)
xor_mask = np.zeros_like(img, dtype=np.bool)
# msg_bits looks like array([ True, False, False, ..., False, False,  True], dtype=bool)
xor_mask[:, :, channel].flat[:len(msg_bits)] = np.ones_like(msg_bits, dtype=np.bool)
</code></pre>

<p>And after assignment to xor mask with channel == 0 or 1 or 2 code works ok, but if channel == [1,2] or smt like this, assignment does not happen </p>

<p>In first example by flattening the slice you don't change the shape and actually the <strike>python</strike> Numpy  doesn't create a new object. so assigning to flattened slice is like assigning to actual slice. But by flattening a 2d array you're changing the shape and hence numpy makes a copy of it.</p>

<p>also you don't need to flatten your slice to add to it:</p>

<pre><code>In [5]: a[:, [0, 2]] += 100

In [6]: a
Out[6]: 
array([[101,   2, 103],
       [104,   5, 106]])
</code></pre>

python arrays python-2.7 numpy slice