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

Derek Homeier derek at astro.physik.uni-goettingen.de
Mon Apr 4 15:30:59 EDT 2011


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




More information about the NumPy-Discussion mailing list