calculations for different columns in a numpy array
<p>I have a 2D array with filled with some values (column 0) and zeros (rest of the columns). I would like to do pretty much the same as I do with MS excel but using numpy, meaning to put into the rest of the columns values from calculations based on the first column. Here it is a MWE:</p>

<pre><code>import numpy as np

a = np.zeros(20, dtype=np.int8).reshape(4,5)

b = [1, 2, 3, 4]

b = np.array(b)

a[:, 0] = b

# don't change the first column
for column in a[:, 1:]:
    a[:, column] = column[0]+1
</code></pre>

<p>The expected output:</p>

<pre><code>array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]], dtype=int8)
</code></pre>

<p>The resulting output:</p>

<pre><code>array([[1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0]], dtype=int8)
</code></pre>

<p>Any help would be appreciated.</p>

<p>Looping is slow and there is no need to loop to produce the array that you want:</p>

<pre><code>&gt;&gt;&gt; a = np.ones(20, dtype=np.int8).reshape(4,5)
&gt;&gt;&gt; a[:, 0] = b
&gt;&gt;&gt; a
array([[1, 1, 1, 1, 1],
       [2, 1, 1, 1, 1],
       [3, 1, 1, 1, 1],
       [4, 1, 1, 1, 1]], dtype=int8)
&gt;&gt;&gt; np.cumsum(a, axis=1)
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])
</code></pre>

<h3>What went wrong</h3>

<p>Let's start, as in the question, with this array:</p>

<pre><code>&gt;&gt;&gt; a
array([[1, 0, 0, 0, 0],
       [2, 0, 0, 0, 0],
       [3, 0, 0, 0, 0],
       [4, 0, 0, 0, 0]], dtype=int8)
</code></pre>

<p>Now, using the code from the question, let's do the loop and see what <code>column</code> actually is:</p>

<pre><code>&gt;&gt;&gt; for column in a[:, 1:]:
...   print(column)
... 
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
</code></pre>

<p>As you can see, <code>column</code> is not the index of the column but the actual values in the column.  Consequently, the following does not do what you would hope:</p>

<pre><code>a[:, column] = column[0]+1
</code></pre>

<h3>Another method</h3>

<p>If we want to loop (so that we can do something more complex), here is another approach to generating the desired array:</p>

<pre><code>&gt;&gt;&gt; b = np.array([1, 2, 3, 4])
&gt;&gt;&gt; np.column_stack([b+i for i in range(5)])
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])
</code></pre>

python numpy