Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating numpy arrays vertically and horizontally

I have a numpy multidimensional array array with the following format:

a  = [[1,2],
      [8,9]]

Then I want to add a list with 3 values (e.g. [4,5,6] at the end horizontally and vertically with the following result:

a = [[1,2,4],
     [8,9,5],
     [4,5,6]]

Do I need to combine row_stack and column_stack somehow?

like image 837
Chielt Avatar asked Mar 14 '14 13:03

Chielt


1 Answers

Here is a way using hstack and vstack:

>>> a  = [[1,2],
...       [8,9]]
>>> x = np.array([4, 5, 6])

>>> b = np.vstack((a, x[:-1]))
>>> print np.hstack((b, x[:, None]))
[[1 2 4]
 [8 9 5]
 [4 5 6]]

You can combine this into one line:

>>> print np.hstack((np.vstack((a, x[:-1])), x[:, None]))
[[1 2 4]
 [8 9 5]
 [4 5 6]]
like image 67
bogatron Avatar answered Sep 30 '22 10:09

bogatron