iterate through number of columns, with variable columns
<p>For example, let's consider this toy code </p>

<pre><code>import numpy as np
import numpy.random as rnd  

a = rnd.randint(0,10,(10,10))
k = (1,2)
b = a[:,k]

for col in np.arange(np.size(b,1)):
    b[:,col] = b[:,col]+col*100
</code></pre>

<p>This code will work when the size of <code>k</code> is bigger than 1. However, with the size equal to 1, the extracted sub-matrix from <code>a</code> is transformed into a row vector, and applying the function in the <code>for</code> loop throws an error.
 Of course, I could fix this by checking the dimension of <code>b</code> and reshaping:</p>

<pre><code>if np.dim(b) == 1: 
    b = np.reshape(b, (np.size(b), 1))
</code></pre>

<p>in order to obtain a column vector, but this is expensive. </p>

<p>So, the question is: what is the best way to handle this situation?
This seems like something that would arise quite often and I wonder what is the best strategy to deal with it. </p>

<p>If you index with a list or tuple, the 2d shape is preserved:</p>

<pre><code>In [638]: a=np.random.randint(0,10,(10,10))
In [639]: a[:,(1,2)].shape
Out[639]: (10, 2)
In [640]: a[:,(1,)].shape
Out[640]: (10, 1)
</code></pre>

<p>And I think <code>b</code> iteration can be simplified to:</p>

<pre><code>a[:,k] += np.arange(len(k))*100
</code></pre>

<p>This sort of calculation will also be easier is <code>k</code> is always a list or tuple, and never a scalar (a scalar does not have a <code>len</code>).</p>

<p><code>np.column_stack</code> ensures its inputs are 2d (and expands at the end if not) with:</p>

<pre><code> if arr.ndim &lt; 2:
     arr = array(arr, copy=False, subok=True, ndmin=2).T
</code></pre>

<p><code>np.atleast_2d</code> does</p>

<pre><code> elif len(ary.shape) == 1:
     result = ary[newaxis,:]
</code></pre>

<p>which of course could changed in this case to</p>

<pre><code> if b.ndim==1:
     b = b[:,None]
</code></pre>

<p>Any ways, I think it is better to ensure the <code>k</code> is a tuple rather than adjust <code>b</code> shape after.  But keep both options in your toolbox.</p>

python numpy for-loop matrix