Numpy matrix multiply different columns

Viewed 71

Is there a quick simple way to multiply multiple columns from a numpy matrix? I'm using the code I show bellow but I was wondering if numpy offers a direct method.

x = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
temp = np.ones(3)
for ind in [0,3]:
    temp *= x[:,ind]
print(temp)

array([  4.,  40., 108.])
2 Answers

Using numpy indexing and numpy.prod. idx can be any number of columns from your array:

>>> idx = [0, 3]
>>> np.prod(x[:, idx], axis=1)

array([  4,  40, 108])

Also equivalent:

x[:, idx].prod(1)

You can multiply the columns since numpy multiplication is element-wise:

x[:, 0] * x[:, 3]

returns

array([  4,  40, 108])
Related