ShadowDoom
ShadowDoom

Reputation: 94

Numpy multiply array with specific column

Im not sure, how I would go about doing this (preferably in an efficient manner) -

import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([[0, 0, 1, 0, 0],
              [0, 0, 1, 0, 0],
              [0, 0, 1, 0, 0],
              [0, 0, 1, 0, 0],
              [0, 0, 1, 0, 0]]

I want to to multiply [1, 2, 3, 4, 5] with [1, 1, 1, 1, 1] (column 3 in b) in an efficient way. Without computing a new array. Efficiency is required to train some of my models faster. This becomes especially useful when dimensions are pretty high.

Any help will be highly appreciated.

Upvotes: 1

Views: 49

Answers (1)

Christian
Christian

Reputation: 1257

Numpy has very efficient matrix/vector operations. If you want the dot product between a and the third column of b you can do

a.dot(b[:,2])
# returns 15

and if you want the element-wise multiplication, you can do

np.multiply(a, b[:,2])
# returns [1, 2, 3, 4, 5]

Upvotes: 1

Related Questions