Search code examples
pythonstringcasting

convert string to float16 in python


I am currently using numpy (I don't know how to make a datatype float16 in python otherwise) as this:

a = np.string_('1.234').astype(np.float16)

then:

type(a)
numpy.float16

Is ther another option? Is it better?

It would be great if you could explain what am I doing when converting the python string into numpy string!

Thank you!


Solution

  • You can go directly from python string to np.float16:

    import numpy as np
    
    f16 = np.float16("1.234")
    print(type(f16))
    
    f16 = np.float16(1.234)  # works as well
    

    Output:

    <class 'numpy.float16'>
    

    Reference: https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.inexact