[Numpy-discussion] Structured array inititialization weirdness

Stéfan van der Walt stefan@sun.ac...
Sat Jun 20 12:35:16 CDT 2009


Hi Erik

2009/6/20 Erik Tollerud <erik.tollerud@gmail.com>:
> 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

The ndarray constructor does its best to guess what kind of data you
are feeding it, but sometimes it needs a bit of help.  By casting your
array to list, you give numpy a hint as to how your data is
partitioned.  In this case, however, I think that hint is the wrong
one.

I prefer to construct arrays explicitly, so there is no doubt what is
happening under the hood:

dt = np.dtype([('a', np.float64), ('b', np.float64)])
np.random.random([2,10]).astype(np.float64).view(dt)

Alternatively, construct the array first, and then fill the elements:

x = np.zeros(10, dtype=dt)
x['a'] = np.random.random(10)
x['b'] = np.random.random(10)

Regards
Stéfan


More information about the Numpy-discussion mailing list