[Numpy-discussion] How to create structured char arrays?

Bruce Southey bsouthey at gmail.com
Tue Apr 5 09:07:37 EDT 2011


On 04/04/2011 02:30 PM, Derek Homeier wrote:
> Hi Bruce,
>
>> I think that I have resolved my issue down to creating a structured
>> string array.
>> I am using numpy version '2.0.0.dev-3c338cb'.
>>
>> Without a structured array, it should be a 2 by 2 array:
>>>>> np.array([('a','b'),('c','d')])
>> array([['a', 'b'],
>>         ['c', 'd']],
>>        dtype='|S1')
>>>>> np.array([('a','b'),('c','d')], dtype='a2')
>> array([['a', 'b'],
>>         ['c', 'd']],
>>        dtype='|S2')
>>
>>
>> It does not work as a structured array:
>>>>> np.array([('a','b'),('c','d')], dtype=[('label','a2'), ('Value',
>> 'a4')])
>> array([('a', 'b'), ('c', 'd')],
>>        dtype=[('label', '|S2'), ('Value', '|S4')])
>>
>> What is the correct dtype argument to use in this case?
>>
> what do you mean by "does not work" - this should give you a 1 by 2
> array
> with 2 fields, i.e.
>
>   >>>  c['label']
> array(['a', 'c'],
>         dtype='|S2')
>   >>>  c['Value']
> array(['b', 'd'],
>         dtype='|S4')
>
> and this should be the same as returned by loadtxt for
>
>   >>>  dt=np.dtype([('label', 'S2'), ('Value', 'S4')])
>   >>>  d = np.loadtxt(StringIO("a\tb\nc\td"), delimiter="\t", dtype=dt)
>
> right? Maybe I should modify my test in #1071 to compare to the full
> array, like
>
> a = np.array([(1,2,3, asbytes('start ')),
>            (4,5,6, asbytes('  ')), (7,8,9.5, asbytes(''))])
> assert_array_equal(x, a)
>
>
> HTH,
> 					Derek
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
Thanks,
Yes I was not thinking carefully enough.

I think it is good to compare the full array because it ensures all 
elements should be the same in value and dtype.

Bruce



More information about the NumPy-Discussion mailing list