[Numpy-discussion] concatenating 1-D arrays to 2D

Bill Baxter wbaxter at gmail.com
Fri Mar 23 02:53:00 EDT 2007


On 3/23/07, Eric Firing <efiring at hawaii.edu> wrote:
> Sebastian Haase wrote:
> > On 3/22/07, Stefan van der Walt <stefan at sun.ac.za> wrote:
> >> On Thu, Mar 22, 2007 at 08:13:22PM -0400, Brian Blais wrote:
> >>> Hello,
> >>>
> >>> I'd like to concatenate a couple of 1D arrays to make it a 2D array, with two columns
> >>> (one for each of the original 1D arrays).  I thought this would work:
> >>>
> >>>
> >>> In [47]:a=arange(0,10,1)
> >>>
> >>> In [48]:a
> >>> Out[48]:array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
> >>>
> >>> In [49]:b=arange(-10,0,1)
> >>>
> >>> In [51]:b
> >>> Out[51]:array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1])
> >>>
> >>> In [54]:concatenate((a,b))
> >>> Out[54]:
> >>> array([  0,   1,   2,   3,   4,   5,   6,   7,   8,   9, -10,  -9,  -8,
> >>>          -7,  -6,  -5,  -4,  -3,  -2,  -1])
> >>>
> >>> In [55]:concatenate((a,b),axis=1)
> >>> Out[55]:
> >>> array([  0,   1,   2,   3,   4,   5,   6,   7,   8,   9, -10,  -9,  -8,
> >>>          -7,  -6,  -5,  -4,  -3,  -2,  -1])
> >>>
> >>>
> >>> but it never expands the dimensions.  Do I have to do this...
> >>>
> >>> In [65]:concatenate((a.reshape(10,1),b.reshape(10,1)),axis=1)
> >>> Out[65]:
> >>> array([[  0, -10],
> >>>         [  1,  -9],
> >>>         [  2,  -8],
> >>>         [  3,  -7],
> >>>         [  4,  -6],
> >>>         [  5,  -5],
> >>>         [  6,  -4],
> >>>         [  7,  -3],
> >>>         [  8,  -2],
> >>>         [  9,  -1]])
> >>>
> >>>
> >>> ?
> >>>
> >>> I thought there would be an easier way.  Did I overlook something?
> >> How about
> >>
> >> N.vstack((a,b)).T
> >>
> > Also mentioned here should be the use of
> > newaxis.
> > As in
> > a[:,newaxis]
> >
> > However I never got a "good feel" for how to use it, so I can't
> > complete the code you would need.
>
> n [9]:c = N.concatenate((a[:,N.newaxis], b[:,N.newaxis]), axis=1)
>
> In [10]:c
> Out[10]:
> array([[  0, -10],
>         [  1,  -9],
>         [  2,  -8],
>         [  3,  -7],
>         [  4,  -6],
>         [  5,  -5],
>         [  6,  -4],
>         [  7,  -3],
>         [  8,  -2],
>         [  9,  -1]])
>

Then of course, there's r_ and c_:

c = numpy.c_[a,b]

c = numpy.r_[a[None],b[None]].T

--bb



More information about the NumPy-Discussion mailing list