Suppose I have a numpy array
X = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
I want to extend this matrix by adding (on the left) the columns resulting by multiplying together all possible pairs of columns. In this example it would become
X = np.array([[1, 2, 3, 2, 6],
[4,5,6,20,24,30],
[7,8,9,56,63,72]])
Where the fourth column is the product of X[:,0]
and X[:,1]
, the fifth column is the product of X[:,0]
and X[:,2]
and the sixth column is the product of X[:,1]
and X[:,2]
.
My Try
I wanted to use np.hstack
for this. However I also know that using loops slows everything down, but I wouldn't know how to do it properly without loops.
for i in range(matrix.shape[1]-1):
for j in range(matrix.shape[1])[i:]:
matrix2 = np.hstack((matrix, (matrix[:,i]*matrix[:,j]).reshape(-1,1))).copy()
The problem with this is that it is slow and also I have to use a different matrix, otherwise it will keep on adding columns.. any better idea?