retrocookie
retrocookie

Reputation: 319

python structured/recarray type conversion behaviour

I'm confused by the behaviour of type conversion when constructing a structured/recarray:

This simple example takes in numerical fields but defines the type as string:

data = [(1.0, 2), (3.0, 4)]
np.array(data, dtype=[('x', str), ('y', int)])

Which produces:

array([('', 2), ('', 4)], dtype=[('x', 'S'), ('y', '<i8')])

So the values were converted to empty strings which is not what you would expect from:

str(1.0)

Which produces the string '1.0'. What's causing this behaviour?

Upvotes: 5

Views: 70

Answers (1)

hpaulj
hpaulj

Reputation: 231540

You need to specify a string width, e.g. 'a3':

>>> np.array([(1.0, 2),(3.0,4)],dtype=[('x','a3'),('y',int)])
array([('1.0', 2), ('3.0', 4)], 
      dtype=[('x', 'S3'), ('y', '<i4')])

Just using str effectively means a string field of 0 bytes - which of course is too small to hold the string rendition of the float.

Upvotes: 6

Related Questions