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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With