Add the same value to every row in a numpy array

Question:

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]]

Answers:

Assuming a the input, you can try:

out = np.c_[a, np.ones((a.shape[0], 1))]

Or:

out = np.hstack([a, np.ones((a.shape[0], 1))])

Output:

array([[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.        ]])
Answered By: mozway

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.        ]]
Answered By: RomanPerekhrest

You can do this:

arr = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]
to_add = [1 for i in range(0, len(arr)) #Making array with all 1s
x = np.column_stack((arr, to_add)) #Add columns together
print(x)
Returns:
[[0 0 0 0 1]
 [0 0 0 0 1]
 [0 0 0 0 1]]
Answered By: mrblue6