Peter Greaves
Peter Greaves

Reputation: 327

Concatenate 3 unidimensional arrays together in numpy

I'm leaving MatLab for numpy and in general it's going ok, but I'm having a nightmare finding a nice pythonic way to do what would have done this in MatLab:

A=[1.0;2.0;3.0;4.0] %Column vector
B=[5.0;6.0;7.0;8.0] %Another one
C=[A,B,B] %4 x 3 matrix

In Python, setting up A like so:

A=np.array([1,2,3,4])
B=np.array([5,6,7,8])

And concatenating like so:

C=np.concatenate((A,B,B),axis=1)

Stacks them one on top of the other, and _C, hstack etc fail as well. I'm guessing I need a nice pyythonic way of turning a (4,) numpy array into a (4,1) array. In my code these vectors are much bigger than this and are created dynamically so I can't just type:

A=np.array([[1],[2],[3],[4]])

Thanks in advance for any help!

Upvotes: 2

Views: 244

Answers (3)

Lee
Lee

Reputation: 31040

>>> C=np.array([A,B,B])
>>> C
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [5, 6, 7, 8]])

or:

>>> C=np.array([A,B,B]).swapaxes(1,0)
>>> C
array([[1, 5, 5],
       [2, 6, 6],
       [3, 7, 7],
       [4, 8, 8]])

Upvotes: 0

YXD
YXD

Reputation: 32511

I would use dstack

>>> A=np.array([1,2,3,4])
>>> B=np.array([5,6,7,8])
>>> np.dstack((A, B, B))
array([[[1, 5, 5],
        [2, 6, 6],
        [3, 7, 7],
        [4, 8, 8]]])

Upvotes: 3

Christoph
Christoph

Reputation: 48390

You can use np.c_[A,B,B], which gives

array([[1, 5, 5],
       [2, 6, 6],
       [3, 7, 7],
       [4, 8, 8]])

Upvotes: 2

Related Questions