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
J_yang
2,9029 gold badges40 silver badges70 bronze badges
2 Answers 2
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
Sheldore
39.2k9 gold badges63 silver badges76 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
vurmux
10k3 gold badges30 silver badges49 bronze badges
Comments
lang-py
a[:, 0] = b.ravel()or withb[:,0].