0

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.

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

All good. Throw a vote to @Chrispresso too if you haven't already - I un-deleted my original (wrong) answer & we ended up answering at almost the same time with the same idea
I did upvote his answer :) I appreciate both of your answers and the time you devoted answering my question. I'm really thankful to you both.
1

How about this?

In [175]: def convert_to_float(val):
     ...:     if isinstance(val, str):
     ...:         return float(val.replace('.', '').replace(',', '.'))
     ...:     elif isinstance(val, int):
     ...:         return float(val)
     ...:     return val

In [176]: a = np.array([758, 762, 762, '1.870,00', '1.870,00', '1.870,00'], dtype=object)

In [177]: np.array([convert_to_float(val) for val in a])
Out[177]: array([ 758.,  762.,  762., 1870., 1870., 1870.])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.