Python structured / repeating type conversion

What confuses me is the behavior of type conversion when building a structured / re-expression:

This simple example accepts numeric fields, but defines the type as a string:

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

What produces:

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

Thus, the values ​​were converted to empty strings, which you do not expect from:

 str(1.0) 

Creates the string '1.0' . What causes this behavior?

+5
source share
1 answer

You need to specify the line width, for example. '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 performance of the float.

+6
source

Source: https://habr.com/ru/post/1239956/


All Articles