[Numpy-discussion] Structured array inititialization weirdness

Francesc Alted faltet@pytables....
Sat Jun 20 13:45:40 CDT 2009


A Saturday 20 June 2009 19:04:03 Erik Tollerud escrigué:
> I've encountered an odd error I don't understand (see the case below):
> the first structured array ("A" in the example) initializes from a
> list of length-2 arrays with no problem, but if I give it a 2-by-2
> array ("B"), it raises a TypeError... Why would it be any different to
> convert the first index of the array into a list?
>
> >>> from numpy import *
> >>> from numpy.random import *
> >>> dt=dtype([('a','f'),('b','f')])
> >>> A=array(list(randn(2,10)),dtype=dt)
> >>> B=array(randn(2,10),dtype=dt)
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: expected a readable buffer object
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion

Besides Stefan's solution, you can use the `numpy.rec` module that provides 
serveral methods allowing more magic so as to recognize inputs in a variety of 
formats.  For your needs, `numpy.rec.fromarrays` seems to work just fine:

In [17]: B = np.rec.fromarrays(np.random.randn(2,10),dtype=dt)

In [18]: B
Out[18]:
rec.array([(1.1266019344329834, -0.091760553419589996),
       (0.018915429711341858, 0.26001507043838501),
       (0.80425763130187988, 0.77772557735443115),
       (0.20478853583335876, 0.10050154477357864),
       (0.67508858442306519, 1.8889480829238892),
       (1.0913237333297729, 1.9765472412109375),
       (-0.64121735095977783, -0.14685167372226715),
       (0.26050111651420593, 0.56423413753509521),
       (-0.047166235744953156, 1.0811176300048828),
       (-2.828101634979248, -0.36026483774185181)],
      dtype=[('a', '<f4'), ('b', '<f4')])

Cheers,

-- 
Francesc Alted


More information about the Numpy-discussion mailing list