I have two numpy arrays. One is a 2d matrix that has 3 columns and 4 rows. The second numpy array is a 1d array with 4 values. Is there a way to append the second numpy array as a column to the first numpy array in Python 2.7?
For example if these were my two numpy arrays:
arr2d = np.matrix(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
column_to_add = np.array([10, 40, 70, 100])
I'd like the output to look like this
[[1, 2, 3, 10],
[4, 5, 6, 40],
[7, 8, 9, 70],
[10, 11, 12, 100]]
I tried using
output = np.hstack((arr2d, column_to_add))
but I got an error that says:
ValueError: all the input arrays must have the same number of dimensions.
Any and all help is appreciated. Thank you so much!
You can use numpy.column_stack
:
import numpy as np
arr2d = np.matrix(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
column_to_add = np.array([10, 40, 70, 100])
output = np.column_stack((arr2d, column_to_add))
Output:
matrix([[ 1, 2, 3, 10],
[ 4, 5, 6, 40],
[ 7, 8, 9, 70],
[ 10, 11, 12, 100]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With