On Tue, Oct 26, 2010 at 8:15 PM, Dewald Pieterse <dewald.piete...@gmail.com> wrote: > Starting with: > >> In [93]: test = >> numpy.array([[[1,1,1],[1,1,1]],[[2,2,2],[2,2,2]],[[3,3,3],[3,3,3]]]) >> >> In [94]: test >> Out[94]: >> array([[[1, 1, 1], >> [1, 1, 1]], >> >> [[2, 2, 2], >> [2, 2, 2]], >> >> [[3, 3, 3], >> [3, 3, 3]]]) >> >> Slicing the complete first row: >> >> In [95]: firstrow = test[0,:,:] >> >> In [96]: firstrow >> Out[96]: >> array([[1, 1, 1], >> [1, 1, 1]]) > > I want to stack firstrow onto test to end up with: > >> ([[[1, 1, 1], >> [1, 1, 1]], >> >> [[1, 1, 1], >> [1, 1, 1]], >> >> [[2, 2, 2], >> [2, 2, 2]], >> >> [[3, 3, 3], >> [3, 3, 3]]] > > > vstack wants the array dimensions to be the same, is this possible without > doing 1 dimensional reshape, the actual data I want to do this on is some > what larger. > >> numpy.vstack((firstrow,test)) >> >> --------------------------------------------------------------------------- >> ValueError Traceback (most recent call >> last) >> >> /mnt/home/home/bmeagle/M/programme/analiseerverwerkteprent.py in >> <module>() >> ----> 1 >> 2 >> 3 >> 4 >> 5 >> >> /usr/lib64/python2.6/site-packages/numpy/core/shape_base.py in vstack(tup) >> 212 >> 213 """ >> --> 214 return _nx.concatenate(map(atleast_2d,tup),0) >> 215 >> 216 def hstack(tup): >> >> ValueError: arrays must have same number of dimensions > > > What is the correct python way to do this?
keep the first dimension or add it back in >>> test = np.array([[[1,1,1],[1,1,1]],[[2,2,2],[2,2,2]],[[3,3,3],[3,3,3]]]) >>> np.vstack((test[:1], test)) array([[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3]]]) >>> np.vstack((test[0][None,...], test)) array([[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3]]]) >>> np.vstack((test[0][None,:,:], test)) array([[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3]]]) I like expand_dims for arbitrary axis, e.g. >>> ax=1 >>> np.concatenate((np.expand_dims(test[:,0,:],ax), test), ax) array([[[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3], [3, 3, 3]]]) Josef > > > -- > Dewald Pieterse > > > _______________________________________________ > NumPy-Discussion mailing list > NumPy-Discussion@scipy.org > http://mail.scipy.org/mailman/listinfo/numpy-discussion > > _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion