Search code examples
pythonstringnumpyfloating-pointnumba

convert float to string numba python numpy array


I am running a @nb.njit function within which I am trying to put an integer within a string array.

import numpy as np
import numba as nb

@nb.njit(nogil=True)
def func():
    my_array = np.empty(6, dtype=np.dtype("U20"))
    my_array[0] = np.str(2.35646)
    return my_array


if __name__ == '__main__':
    a = func()
    print(a)

I am getting the following error :

numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Invalid use of Function(<class 'str'>) with argument(s) of type(s): (float64)

Which function am I supposed to use to do the conversion from float to string within numba ?


Solution

  • The numpy.str function is not supported so far. A list of all the supported numpy functions is available on Numba's website.

    The built-in str is not supported either. This can be checked on the supported Python features page.

    The only way to do what you are trying would be to somehow make a function that converts a float to a string, using only the features of Python and Numpy supported by Numba.

    Before going in this direction, I would nevertheless reconsider the necessity to convert floats into strings. It may not be very efficient and you may lose the benefit of jitting a few functions by adding some overhead due to the conversion of floats to string.

    Of course, this is hard to tell without knowing more about the project.