Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
retrocookie Avatar asked Jan 06 '16 04:01

retrocookie


1 Answers

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.

like image 178
hpaulj Avatar answered Oct 31 '22 20:10

hpaulj