Add the same value to every row in a numpy array

Advertisements

I have a numpy array that looks like this:

[[0.67058825 0.43529415 0.33725491]
[0.01568628 0.30980393 0.96862751]
[0.24705884 0.63529414 0.29411766]
[0.27843139 0.63137257 0.37647063]
[0.26274511 0.627451   0.33333334]
[0.25098041 0.61960787 0.30980393]]

I want to add a 1 to every row like this:

[[0.67058825 0.43529415 0.33725491 1]
[0.01568628 0.30980393 0.96862751 1]
[0.24705884 0.63529414 0.29411766 1]
[0.27843139 0.63137257 0.37647063 1]
[0.26274511 0.627451   0.33333334 1]
[0.25098041 0.61960787 0.30980393 1]]

>Solution :

Simply with numpy.insert to insert the needed value into required position along the given axis:

arr = np.insert(arr, arr.shape[1], 1, axis=1)

[[0.67058825 0.43529415 0.33725491 1.        ]
 [0.01568628 0.30980393 0.96862751 1.        ]
 [0.24705884 0.63529414 0.29411766 1.        ]
 [0.27843139 0.63137257 0.37647063 1.        ]
 [0.26274511 0.627451   0.33333334 1.        ]
 [0.25098041 0.61960787 0.30980393 1.        ]]

Leave a Reply Cancel reply