Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a column to a 2d numpy array in Python 2.7?

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!

like image 881
CSLearner Avatar asked Jan 03 '23 20:01

CSLearner


1 Answers

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]])
like image 140
FJSevilla Avatar answered Jan 06 '23 09:01

FJSevilla