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.

Blg Khalil
  • 349
  • 1
  • 3
  • 16

2 Answers2

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

PeptideWitch
  • 2,239
  • 14
  • 30
  • 1
    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 – PeptideWitch Nov 21 '21 at 23:34
  • 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. – Blg Khalil Nov 21 '21 at 23:40
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.])
Chrispresso
  • 3,660
  • 2
  • 19
  • 31