[Numpy-discussion] Best representation for array of points, or, how to distinguish a Nx1 array of points from a Nx3 array of scalars
Robert Kern
robert.kern@gmail....
Thu Oct 4 14:51:09 CDT 2007
Edson Tadeu wrote:
> For now, I solved it using a view with a different type:
>
> from numpy import *
> N = 5
> a=zeros(N,'3f8')
> b=a.view()
> b.dtype='f8'
> b.shape = N,3
Note that this doesn't quite do what you want. I was wrong about the dtype='3f8'
syntax: it just gives you a regular float array with the shape changed
appropriately (at least in recent version of numpy; if you are getting something
different, what version are you using?).
In [24]: from numpy import *
In [25]: N = 5
In [26]: zeros(N, dtype='3f8')
Out[26]:
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
If you want a shape-(N,) record array, you need a different dtype:
In [28]: zeros(N, dtype='f8,f8,f8')
Out[28]:
array([(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0),
(0.0, 0.0, 0.0)],
dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8')])
In [31]: zeros(N, dtype=dtype([('x', float), ('y', float), ('z', float)]))
Out[31]:
array([(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0),
(0.0, 0.0, 0.0)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
To go back, you can give .view() an argument:
In [30]: zeros(N, dtype='f8,f8,f8').view(dtype((float, 3)))
Out[30]:
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
--
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