vstack and hstack

Suppose you have a $3\times 3$ array to which you wish to add a row or column. Adding a row is easy with np.vstack:

In [x]: a = np.ones((3, 3))
In [x]: np.vstack( (a, np.array((2,2,2))) )
Out[x]: 
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])

Adding a column requires a bit more work, however. You can't use np.hstack directly:

In [x]: a = np.ones((3, 3))
In [x]: np.hstack( (a, np.array((2,2,2))) )

... [Traceback information] ...
ValueError: all the input arrays must have same number of dimensions

This is because np.hstack cannot concatenate two arrays with different numbers of rows. Schematically:

[[ 1.,  1.,  1.],       [2., 2., 2.]
 [ 1.,  1.,  1.],   +                   = ?
 [ 1.,  1.,  1.]]

We can't simply transpose our new row, either, because it's a one-dimensional array and its transpose is the same shape as the original. So we need to reshape it first:

In [x]: a = np.ones((3, 3))
In [x]: b = np.array((2,2,2)).reshape(3,1)
In [x]: b
array([[2],
       [2],
       [2]])
In [x]: np.hstack((a, b))
Out[x]:
array([[ 1.,  1.,  1.,  2.],
       [ 1.,  1.,  1.,  2.],
       [ 1.,  1.,  1.,  2.]])