[Numpy-discussion] printing structured arrays

josef.pktd@gmai... josef.pktd@gmai...
Mon Mar 8 13:30:17 CST 2010


On Mon, Mar 8, 2010 at 2:24 PM, Skipper Seabold <jsseabold@gmail.com> wrote:
> On Mon, Mar 8, 2010 at 2:17 PM,  <josef.pktd@gmail.com> wrote:
>> On Mon, Mar 8, 2010 at 2:04 PM, Skipper Seabold <jsseabold@gmail.com> wrote:
>>> On Mon, Mar 8, 2010 at 2:01 PM,  <josef.pktd@gmail.com> wrote:
>>>> On Mon, Mar 8, 2010 at 1:55 PM, Tim Michelsen
>>>> <timmichelsen@gmx-topmail.de> wrote:
>>>>> Hello,
>>>>> I am also looking into the convertsion from strcutured arrays to ndarray.
>>>>>
>>>>>> I've just started playing with numpy and have noticed that when printing
>>>>>> a structured array that the output is not nicely formatted. Is there a
>>>>>> way to make the formatting look the same as it does for an unstructured
>>>>>> array?
>>>>>
>>>>>> Output is:
>>>>>> ### ndarray
>>>>>> [[ 1.   2. ]
>>>>>>  [ 3.   4.1]]
>>>>>> ### structured array
>>>>>> [(1.0, 2.0) (3.0, 4.0999999999999996)]
>>>>> How could we make this structured array look like the above shown
>>>>> ndarray with shape (2, 2)?
>>>>
>>>> .view(float) should do it, to created a ndarray view of the structured
>>>> array data
>>>>
>>>
>>> Plus a reshape.  I usually know how many columns I have, so I put in
>>> axis 1 and leave axis 0 as -1.
>>>
>>> In [21]: a.view(float).reshape(-1,2)
>>> Out[21]:
>>> array([[ 1. ,  2. ],
>>>       [ 3. ,  4.1]])
>>
>>
>> a.view(float).reshape(len(a),-1)     #if you don't want to count columns
>>
>> I obviously haven't done this in a while.
>> And of course, it only works if all elements of the structured array
>> have the same type.
>>
>
> For the archives with heterogeneous dtype.
>
> import numpy as np
>
> b = np.array([(1.0, 'string1', 2.0), (3.0, 'string2', 4.1)],
> dtype=[('x', float),('str_var', 'a7'),('y',float)])
>
> b[['x','y']].view(float).reshape(len(b),-1) # note the list within list syntax
>
> #array([[ 1. ,  2. ],
> #       [ 3. ,  4.1]])

nice, I've never seen selection of multiple columns before. I didn't
know it is possible to get a subset of columns this way

>>> b[['x','y']]
array([(1.0, 2.0), (3.0, 4.0999999999999996)],
      dtype=[('x', '<f8'), ('y', '<f8')])
>>> b['x']
array([ 1.,  3.])
>>> b[['x']]
array([(1.0,), (3.0,)],
      dtype=[('x', '<f8')])

Josef


>
> Skipper
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the NumPy-Discussion mailing list