0

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?

2 Answers 2

2

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

Comments

0
a = np.zeros((2 , 2))
b = np.ones((1 ,2))
np.concatenate([b , np.array([a[0]])])

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.