[Numpy-discussion] Creating a 1-d structured array
Derek Homeier
derek at astro.physik.uni-goettingen.de
Fri May 13 15:11:44 EDT 2011
Hi,
just a comment since I first thought the solution below might not be
what Bruce
was looking for, but having realised it's probably what he's been
asking for...
On 13 May 2011, at 17:20, josef.pktd at gmail.com wrote:
> On Fri, May 13, 2011 at 10:58 AM, Bruce Southey <bsouthey at 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.
...
>
> 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)])
>
> 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
>
>>>> a1 = np.array([1,2, 3,4, 5,6])
>>>> a1.dtype
> dtype('int32')
>>>> a1.dtype = np.dtype([('foo', int)])
>>>> a1
> array([(1,), (2,), (3,), (4,), (5,), (6,)],
> dtype=[('foo', '<i4')])
This is a 1-d structured array, yet a is in fact not the same as
a['foo']:
>>> a['foo']
array([ 1, 2, 3, 4, 5, 6])
>>> a['foo'].shape
(6,)
>>> a.shape
(6,)
>>> a['foo']+np.arange(6)
array([ 1, 3, 5, 7, 9, 11])
>>> a+np.arange(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and
'numpy.ndarray'
>>> a[0]+1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'numpy.void' and 'int'
Thus I am wondering why broadcasting should not be possible in this
case,
and if it really isn't, the first error message certainly is not very
helpful... (maybe
inevitably though, since type() of a structured array is the same as
for a "plain"
array (unlike for a record array).
Cheers,
Derek
More information about the NumPy-Discussion
mailing list