assume matrix is 2d numpy (MxN) array and vector is 1d array (1xN) - both have same N rows. I need to add to each column in matrix value of same row element in vector:
[[1 2 3],
[4 5 6]]
[0.1 0.2]
result:
[[1.1 2.1 3.1],
[4.2 5.2 6.2]]
CodePudding user response:
you can use numpy.reshape(-1,1)
and get what you want:
l1 = np.array([[1, 2, 3],[4, 5 , 6]])
l2 = np.array([0.1, 0.2]).reshape(-1,1)
l1 l2
Output:
array([[1.1, 2.1, 3.1],
[4.2, 5.2, 6.2]])
CodePudding user response:
Taking advantage of numpy broadcasting, you can do a b[:, None]
:
a = np.arange(1,7).reshape((2, 3))
b = np.array([0.1, 0.2])
a b[:, None]
array([[1.1, 2.1, 3.1],
[4.2, 5.2, 6.2]])
Or:
a b[:, np.newaxis]
array([[1.1, 2.1, 3.1],
[4.2, 5.2, 6.2]])