[Numpy-discussion] field names on numpy arrays
Robert Kern
robert.kern at gmail.com
Wed Jun 3 17:03:49 EDT 2009
On Wed, Jun 3, 2009 at 15:26, <josef.pktd at gmail.com> wrote:
> 2009/6/3 Stéfan van der Walt <stefan at sun.ac.za>:
>> Hi Jon
>>
>> 2009/6/3 D2Hitman <j.m.girven at warwick.ac.uk>:
>>> I understand record arrays such as:
>>> a_array =
>>> np.array([(0.,1.,2.,3.,4.),(1.,2.,3.,4.,5.)],dtype=[('a','f'),('b','f'),('c','f'),('d','f'),('e','f')])
>>> do this with field names.
>>> a_array['a'] = array([ 0., 1.], dtype=float32)
>>> however i seem to lose simple operations such as multiplication (a_array*2)
>>> or powers (a_array**2).
>>
>> As a workaround, you can have two views on your data:
>>
>> n [39]: x
>> Out[39]:
>> 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 [40]: x = x_dict.view(np.float32)
>>
>> In [41]: x**2
>> Out[41]: array([ 0., 1., 4., 9., 16., 1., 4., 9., 16.,
>> 25.], dtype=float32)
>>
>> Then you can manipulate the same data using two different "interfaces".
>
> Why does it not preserve "shape", to do e.g. np.mean by axis?
It does preserve the shape. The input and output are both 1D. If you
need a different shape (e.g. re-interpreting the record as another
axis), you need to reshape it yourself. numpy can't guess what you
want.
--
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