Reputation: 533
I want to add the values in a numpy array to the values in a specific row of a numpy matrix.
Given:
A = [[0, 0], [0, 0]]
b = [1, 1]
I want to add b to the values in the first row in A. The expected output is:
[[1, 1], [0, 0]]
I tried using the "+" operator, but got an error:
>>> import numpy
>>> a = numpy.zeros(shape=(2,2))
>>> a
array([[ 0., 0.],
[ 0., 0.]])
>>> b = numpy.ones(shape=(1,2))
>>> b
array([[ 1., 1.]])
>>> a[0, :] += b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: non-broadcastable output operand with shape (2,) doesn't match the broadcast shape (1,2)
What is the best way to do this?
Upvotes: 0
Views: 333
Reputation: 5414
a = np.zeros((2 , 2))
b = np.ones((1 ,2))
np.concatenate([b , np.array([a[0]])])
Upvotes: 0
Reputation: 251156
There's a difference between b = [1, 1]
and b = [[1, 1]]
. a[0, :] += b
failed for you because broadcasting is not possible in this case.
If b
can contain variable number of rows then we can take a slice of a
using b
's length and add b
to it.
>>> a = numpy.zeros(shape=(2,2))
>>> b = numpy.ones(shape=(1,2))
>>> a[:len(b)] += b
>>> a
array([[ 1., 1.],
[ 0., 0.]])
Or if b
contains only one row then:
>>> a = numpy.zeros(shape=(2,2))
>>> a[0] += b[0]
>>> a
array([[ 1., 1.],
[ 0., 0.]])
Upvotes: 2