Home > Software engineering >  How to add a array to a column of a matrix? (python numpy)
How to add a array to a column of a matrix? (python numpy)

Time:12-16

Like this:

import numpy as np
a = np.zeros((3,3))
b = np.ones((3,1))
a[:,2]  = b

expected:

a = 
0,0,1
0,0,1
0,0,1

in fact:

ValueError: non-broadcastable output operand with shape (3,) doesn't match the broadcast shape (3,3)

What should I do?

CodePudding user response:

Specifying the range of column is required

e.g. a[:,0:1] for column 0, a[:,1:2] for column 1, and a[:,2:] for column 2.

import numpy as np
a = np.zeros((3,3))
b = np.ones((3,1))
a[:,2:]  = b

output:

array([[0., 0., 1.],
       [0., 0., 1.],
       [0., 0., 1.]])
  • Related