[Numpy-discussion] create an object array with named dtype

Robert Kern robert.kern at gmail.com
Thu Nov 4 12:28:20 EDT 2010


On Thu, Nov 4, 2010 at 11:08, Skipper Seabold <jsseabold at gmail.com> wrote:
> I just ran into this and am kind of baffled.  There are other ways I
> could do this so it's not a huge deal, but I'm wondering if this is a
> bug.  I want a (named) structured array with an object dtype.  Is this
> possible?
>
> For example
>
> In [68]: import numpy as np
>
> In [69]: A = np.array((np.arange(10)[:,None], 3, 4.5), dtype=[("prob", float, (1
> 0,1)),
>   ....:         ("m1", float),("m2", float)])
>
> In [70]: B = np.array((np.arange(10,20)[:,None], 3, 4.5), dtype=[("prob", float,
>  (10,1)),
>   ....:         ("m1", float),("m2", float)])
>
> This works fine.
>
> In [71]: C = np.empty(2, dtype=object)
>
> In [72]: C[0] = A
>
> In [73]: C[1] = B
>
> In [74]: np.all(C[0] == A)
> Out[74]: True
>
> In [75]: np.all(C[1] == B)
> Out[75]: True
>
> This doesn't.  Looks like it takes a bad view on the array part (?)
>
> In [76]: D = np.empty(2, dtype=[("n1",object),("n2", object)])
>
> In [77]: D["n1"] = A
>
> In [78]: D["n2"] = B
>
> In [79]: np.all(D["n1"] == A)
> Out[79]: False
>
> In [80]: np.all(D["n2"] == B)
> Out[80]: False

Yes, there is a problem:

[~]
|6> D['n1']
array([ (array([[  3.98154716e-303],
       [  2.15123073e-314],
       [  1.16902381e-291],
       [  3.99988181e-303],
       [  6.33886224e-321],
       [ -1.79678332e+182],
       [  1.69759663e-313],
       [  3.98154716e-303],
       [  3.96089848e-303],
       [  3.96089848e-303]]), 3.0, 4.5),
       (array([[  0.00000000e+000],
       [  4.94065646e-324],
       [  1.10229260e-291],
       [  3.99988181e-303],
       [  1.16899398e-291],
       [  1.83328798e-288],
       [  3.98154716e-303],
       [  2.15124483e-314],
       [  1.16898711e-291],
       [  3.99632165e-303]]), 3.0, 4.5)], dtype=object)

The data in the A['prob'] didn't get copied correctly when it got
assigned. If you assign D[0]['n1'] and D[1]['n1'] separately, it
works.

[~]
|12> D[0]['n1'] = A

[~]
|16> D[1]['n1'] = A

[~]
|17> D
array([ ((array([[ 0.],
       [ 1.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 5.],
       [ 6.],
       [ 7.],
       [ 8.],
       [ 9.]]), 3.0, 4.5), None),
       ((array([[ 0.],
       [ 1.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 5.],
       [ 6.],
       [ 7.],
       [ 8.],
       [ 9.]]), 3.0, 4.5), None)],
      dtype=[('n1', '|O4'), ('n2', '|O4')])


-- 
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