Inserting one item on a matrix
<p>How do I insert a single element into an array on numpy.  I know how to insert an entire column or row using the insert and axis parameter.  But how do I insert/expand by one.</p>

<p>For example, say I have an array:</p>

<pre><code>1 1 1
1 1 1
1 1 1
</code></pre>

<p>How do I insert 0 (on the same row), say on (1, 1) location, say:</p>

<pre><code>1 1 1
1 0 1 1
1 1 1
</code></pre>

<p>is this doable?  If so, then how do you do the opposite (on the same column), say:</p>

<pre><code>1 1 1
1 0 1
1 1 1
  1
</code></pre>

<p>Numpy has something that <em>looks</em> like ragged arrays, but those are arrays of objects, and probably not what you want. Note the difference in the following:</p>

<pre><code>In [27]: np.array([[1, 2], [3]])
Out[27]: array([[1, 2], [3]], dtype=object)

In [28]: np.array([[1, 2], [3, 4]])
Out[28]:
array([[1, 2],
       [3, 4]])
</code></pre>

<p>If you want to insert <code>v</code> into row/column <code>i/j</code>, you can do so by padding the other rows. This is easy to do:</p>

<pre><code>In [29]: a = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])

In [30]: i, j, v = 1, 1, 3

In [31]: np.array([np.append(a[i_], [0]) if i_ != i else np.insert(a[i_], j, v) for i_ in range(a.shape[1])])
Out[31]:
array([[1, 1, 1, 0],
       [1, 3, 1, 1],
       [1, 1, 1, 0]])
</code></pre>

<p>To pad along columns, not rows, first transpose <code>a</code>, then perform this operation, then transpose again.</p>

python numpy