
On Fri, May 13, 2011 at 10:58 AM, Bruce Southey <bsouthey@gmail.com> wrote:
Hi, How do you create a 'single' structured array using np.array()? Basically I am attempting to do something like this that does not work: a=np.array([1,2, 3,4, 5,6], dtype=np.dtype([('foo', int)]))
I realize that this is essentially redundant as if A is an 1-d array then a structured array with a named field 'foo' is the same thing - A would be A['foo'], just shorter.
So if that is valid then a clearer error message is required to indicate this and provide the suitable error message to address ticket 1264 (http://projects.scipy.org/numpy/ticket/1264).
$ python Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) [GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> a=np.array([1,2, 3,4, 5,6], dtype=np.dtype([('foo', int)])) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected a readable buffer object >>> np.array([(1,2), (3,4), (5,6)], dtype=np.dtype([('foo', int), ('foo2', int)])) array([(1, 2), (3, 4), (5, 6)], dtype=[('foo', '<i8'), ('foo2', '<i8')]) >>> a=np.array([(1), (3), (5)], dtype=np.dtype([('foo', int)])) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected a readable buffer object >>> np.array([(1), (3), (5)], dtype=np.dtype(int)) array([1, 3, 5]) >>> np.array((1,2, 3,4, 5,6)) array([1, 2, 3, 4, 5, 6])
Using a view works, (and direct assignment of dtype)
a=np.array([1,2, 3,4, 5,6]).view(([('foo', int)])) a array([(1,), (2,), (3,), (4,), (5,), (6,)], dtype=[('foo', '<i4')]) b = a.copy() b array([(1,), (2,), (3,), (4,), (5,), (6,)], dtype=[('foo', '<i4')])
a1 = np.array([1,2, 3,4, 5,6]).astype([('foo', int)])
a1 = np.array([1,2, 3,4, 5,6]) a1.dtype
Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> a1 = np.array([1,2, 3,4, 5,6]).astype([('foo', int)]) TypeError: expected a readable buffer object dtype('int32')
a1.dtype = np.dtype([('foo', int)]) a1 array([(1,), (2,), (3,), (4,), (5,), (6,)], dtype=[('foo', '<i4')])
Josef
Thanks Bruce _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion