Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy matrix multiply different columns

Tags:

python

numpy

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.])
like image 805
Miguel Avatar asked Sep 21 '26 13:09

Miguel


1 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)
like image 142
user3483203 Avatar answered Sep 24 '26 03:09

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!