4

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!

1
  • Correct the number of dimensions: np.concatenate((arr2d, column_to_add[:,None]), axis=1). The [:,None] makes the 1d array into a 2d column array. Commented Jun 20, 2017 at 16:09

1 Answer 1

10

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.