Convert the Strings and Integers of a NumPy Array into Floats

I have a numpy array:

array([758, 762, 762, ..., '1.870,00', '1.870,00', '1.870,00'],
      dtype=object)

and I want to get:

array([758., 762., 762., ..., 1870., 1870., 1870.])

I’ve tried several methods to turn all of its elements into floats but failed each time.

>Solution :

How about this:

import numpy as np

arr = np.array([10, '1.870,00'])

def custom_parse(x):
    if isinstance(x, str):
        new_str = x.replace('.', '').replace(',', '.')
        return float(new_str)
    else:
        return float(x)

new_array = np.array(list(map(custom_parse, arr)))

print(new_array)

It’s tricky because your string representation of a number isn’t easy to cast as a float, so you’ll probably have to parse it manually

Leave a Reply