[Numpy-discussion] What am I missing about concatenate?

Tim Hochberg tim.hochberg at cox.net
Thu Jun 1 11:47:07 EDT 2006


Christopher Barker wrote:

> I want to take two (2,) arrays and put them together into one (2,2) 
> array. I thought one of these would work:
>
> >>> N.concatenate(((1,2),(3,4)),0)
> array([1, 2, 3, 4])
> >>> N.concatenate(((1,2),(3,4)),1)
> array([1, 2, 3, 4])
>
> Is this the best I can do?
>
> >>> N.concatenate(((1,2),(3,4))).reshape(2,2)
> array([[1, 2],
>        [3, 4]])
>
> Is it because the arrays I'm putting together are rank-1?

Yes.

You need to add a dimension somehow. There are (at least) two ways to do 
this. If you are using real arrays, use newaxis:

     >>> a
    array([0, 1, 2])
     >>> b
    array([3, 4, 5])
     >>> concatenate([a[newaxis], b[newaxis]], 0)
    array([[0, 1, 2],
           [3, 4, 5]])

Alternatively, if you don't know that 'a' and 'b' are arrays or you just 
hate newaxis, wrap the arrays in [] to give them an extra dimension. 
This tends to look nicer, but I suspect has poorer performance than 
above (haven't timed it though):

     >>> concatenate([[a], [b]], 0)
    array([[0, 1, 2],
           [3, 4, 5]])


-tim

>
> >>> N.__version__
> '0.9.6'
>
> -Chris
>
>
>
>
>






More information about the NumPy-Discussion mailing list