Adding columns to matrix in python

The function you are looking for in numpy.hstack and numpy.ones:

For example,

import numpy as np

X = np.random.uniform(size=(10,3))
n,m = X.shape # for generality
X0 = np.ones((n,1))
Xnew = np.hstack((X,X0))

print(X)
[[ 0.78614426  0.24150772  0.94330932]
 [ 0.60088812  0.20427371  0.19453546]
 [ 0.31853252  0.31669057  0.82782995]
 [ 0.71749368  0.54609844  0.74924888]
 [ 0.86883981  0.54634575  0.83232409]
 [ 0.89313181  0.8006561   0.05072146]
 [ 0.79492088  0.07750024  0.45762175]
 [ 0.92350837  0.20587178  0.76987197]
 [ 0.0092076   0.0044617   0.04673518]
 [ 0.69569363  0.3315923   0.15093861]]

print(X0)
[[ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]
 [ 1.]]

print(Xnew)
[[ 0.78614426  0.24150772  0.94330932  1.        ]
 [ 0.60088812  0.20427371  0.19453546  1.        ]
 [ 0.31853252  0.31669057  0.82782995  1.        ]
 [ 0.71749368  0.54609844  0.74924888  1.        ]
 [ 0.86883981  0.54634575  0.83232409  1.        ]
 [ 0.89313181  0.8006561   0.05072146  1.        ]
 [ 0.79492088  0.07750024  0.45762175  1.        ]
 [ 0.92350837  0.20587178  0.76987197  1.        ]
 [ 0.0092076   0.0044617   0.04673518  1.        ]
 [ 0.69569363  0.3315923   0.15093861  1.        ]]

I found the numpy.c_ function pretty handy at adding a column to an matrix. The following code would add a column with all zeros to the matrix.

import numpy as np

np.c_[np.ones((100,1)),X]

Here, X is the original matrix.

Tags:

Python

Numpy