[Numpy-discussion] View ND Homogeneous Record Array as (N+1)D Array?

Robert Kern robert.kern@gmail....
Mon Mar 17 15:55:10 CDT 2008


On Mon, Mar 17, 2008 at 3:44 PM, Alexander Michael <lxander.m@gmail.com> 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')])

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
 -- Umberto Eco


More information about the Numpy-discussion mailing list