0

I have these arrays.

 a = np.array([[1,2,3],[3,4,5],[4,5,6]])
 b = np.array([-1, -2, -3])

I want to change the some of elements of a with the elements of b like so:

a = [[1, -1, -1],
     [3, -2, -2],
     [4, -3, -3]]

I tried: a[:,1:]=b but got an exception:

ValueError: could not broadcast input array from shape (3) into shape (3,2)

What is the correct way to broadcast b into a?

3
  • 2
    a[:, 1:] = b[:, None] make b (3,1) shaped Commented Jul 31, 2020 at 22:15
  • @hpaulj Thanks that work. I did try a[:, 1:] = b.T to reshape to (3,1) but that did not work. Why did it not work? Seem that b[:, None] is the way to transpose a row vector to a column vector. Commented Jul 31, 2020 at 23:42
  • 1
    @SunBear: NumPy's idea of a transpose is n-dimensional, not 2-dimensional. It reverses the order of an array's axes. When there's only one axis, this changes nothing. Commented Aug 1, 2020 at 0:13

1 Answer 1

3

You're trying to treat b as a column, but the broadcasting rules will try to copy b into the rows of a[:, 1:]. That won't work.

Instead, transpose a and copy b into the rows of the transpose:

a.T[1:] = b
Sign up to request clarification or add additional context in comments.

5 Comments

If the memory-layout of a is such that a.T is a copy, this won't affect a, right?
@Ehsan: a.T cannot be a copy. It's not like reshape. a.T[1:] = b is guaranteed to write into a.
It's the reshape after a transpose that makes a copy. Still I prefer reshaping b so it broadcasts.
Thanks. Your approach works. Will your approach be more computationally demanding than @hpaulj approach given that the size of a is typically larger than b?
@SunBear the transpose (like slicing and most reshaping) is done lazily in numpy, only metadata are modified. The cost does therefore not depend on data size.

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.