3

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 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That is precisely what I was looking for!
1

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

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

returns

array([  4,  40, 108])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.