Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading