1

I am trying to replace one or several columns with a new array with the same length.

a = np.array([[1,2,3],[1,2,3],[1,2,3]])
b = np.array([[0,0,0])
a[:, 0] = b

I got an error of ValueError: could not broadcast input array from shape (3,1) into shape (3). However this works when b has multiple columns.

a = np.array([[1,2,3],[1,2,3],[1,2,3]])
b = np.array([[0,7],[0,7],[0,7]])
a[:, 0:2] = b
array([[0, 7, 3],
 [0, 7, 3],
 [0, 7, 3]])

How can I efficiently replace a column with another array?

Thanks

J

asked Apr 12, 2019 at 15:27
1
  • Supply flattened version - a[:, 0] = b.ravel() or with b[:,0]. Commented Apr 12, 2019 at 15:30

2 Answers 2

3

Your example will work fine if you use the following just like you are using a[:, 0:2] = b. [:, 0:1] is effectively just the first column

a = np.array([[1,2,3],[1,2,3],[1,2,3]])
b = np.array([[0],[0],[0]])
a[:, 0:1] = b
# array([[0, 2, 3],
# [0, 2, 3],
# [0, 2, 3]])
answered Apr 12, 2019 at 15:31
Sign up to request clarification or add additional context in comments.

Comments

2

You have an incorrect shape of b. You should pass an ordinary 1D array to it if you want to replace only one column:

a = np.array([[1,2,3],[1,2,3],[1,2,3]])
b = np.array([0,0,0])
a[:, 0] = b
a

Returns:

array([[0, 2, 3],
 [0, 2, 3],
 [0, 2, 3]])
answered Apr 12, 2019 at 15:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.