On Mon, Mar 17, 2008 at 4:55 PM, Robert Kern <[EMAIL PROTECTED]> wrote: > On Mon, Mar 17, 2008 at 3:44 PM, Alexander Michael <[EMAIL PROTECTED]> wrote: > > Is there a way to view an N-dimensional array with a *homogeneous* > > record dtype as an array of N+1 dimensions? An example will make it > > clear: > > > > import numpy > > a = numpy.array([(1.0,2.0), (3.0,4.0)], dtype=[('A',float),('B',float)]) > > b = a.view(...) # do something magical > > print b > > array([[ 1., 2.], > > [ 3., 4.]]) > > b[0,0] = 0.0 > > print a > > [(0.0, 2.0) (3.0, 4.0)] > > > Just use a.view(float) and then reshape as appropriate. > > In [1]: import numpy > > In [2]: a = numpy.array([(1.0,2.0), (3.0,4.0)], > dtype=[('A',float),('B',float)]) > > In [3]: a.view(float) > Out[3]: array([ 1., 2., 3., 4.]) > > In [4]: b = _ > > In [5]: b.shape = a.shape + (-1,) > > In [6]: b > Out[6]: > > array([[ 1., 2.], > [ 3., 4.]]) > > In [7]: b[0,0] = 0.0 > > In [8]: a > Out[8]: > array([(0.0, 2.0), (3.0, 4.0)], > dtype=[('A', '<f8'), ('B', '<f8')])
Cool. Thanks. I made a little function for doing this if anyone else is interested: import numpy def unpacked_view(x): """Return a view of `x` with its fields unpacked. Requires all fields to have the same type. Examples -------- >>> a = numpy.array( ... [(1.0,2.0), (3.0,4.0), (5.0,6.0)], ... dtype=[('A',float),('B',float)]) >>> u = unpacked_view(a) >>> u array([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) >>> u.shape (3, 2) """ if x.dtype.names: ftypes = set([t for n,t in x.dtype.descr]) assert(len(ftypes) == 1) ftype = ftypes.pop() y = x.view(ftype) unpacked_shape = x.shape + (-1,) y.shape = unpacked_shape return y else: return x _______________________________________________ Numpy-discussion mailing list Numpy-discussion@scipy.org http://projects.scipy.org/mailman/listinfo/numpy-discussion