[Numpy-discussion] another view puzzle
Christopher Barker
Chris.Barker at noaa.gov
Wed Jun 3 16:46:52 EDT 2009
josef.pktd at gmail.com wrote:
>>>> import numpy as np
>>>> x = np.array([(0.0, 1.0, 2.0, 3.0, 4.0), (1.0, 2.0, 3.0, 4.0, 5.0)],
> dtype=[('a', '<f4'), ('b', '<f4'), ('c', '<f4'), ('d', '<f4'),
> ('e', '<f4')])
>
>>>> xvm = x.view(np.matrix)
>>>> xvm
> matrix([[(0.0, 1.0, 2.0, 3.0, 4.0), (1.0, 2.0, 3.0, 4.0, 5.0)]],
> dtype=[('a', '<f4'), ('b', '<f4'), ('c', '<f4'), ('d', '<f4'),
> ('e', '<f4')])
I think you need to tell numpy more about how you want to turn the
struct array into a matrix -- a custom data type could be anything,
numpy sees x as a (2,) sized array of a custom structure -- there is no
one way to turn it into a matrix. I think this may be what you want:
In [32]: x
Out[32]:
array([(0.0, 1.0, 2.0, 3.0, 4.0), (1.0, 2.0, 3.0, 4.0, 5.0)],
dtype=[('a', '<f4'), ('b', '<f4'), ('c', '<f4'), ('d', '<f4'),
('e', '<f4')])
In [33]: x.shape
Out[33]: (2,)
In [34]: x2 = x.view(dtype=np.float32).reshape((2,5))
In [35]: x2
Out[35]:
array([[ 0.00000000e+00, 4.60060299e-41, 8.96831017e-44,
2.30485571e-41, 4.60074312e-41],
[ 4.60060299e-41, 8.96831017e-44, 2.30485571e-41,
4.60074312e-41, 5.74868682e-41]], dtype=float32)
In [36]: xvm = np.asmatrix(x2)
In [37]: xvm
Out[37]:
matrix([[ 0.00000000e+00, 4.60060299e-41, 8.96831017e-44,
2.30485571e-41, 4.60074312e-41],
[ 4.60060299e-41, 8.96831017e-44, 2.30485571e-41,
4.60074312e-41, 5.74868682e-41]], dtype=float32)
In [38]: xvm * 2
Out[38]:
matrix([[ 0.00000000e+00, 9.20120598e-41, 1.79366203e-43,
4.60971143e-41, 9.20148624e-41],
[ 9.20120598e-41, 1.79366203e-43, 4.60971143e-41,
9.20148624e-41, 1.14973736e-40]])
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list