将 NumPy 数组的字符串和整数转换为浮点数

Convert the Strings and Integers of a NumPy Array into Floats

我有一个 numpy 数组:

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

我想得到:

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

我尝试了几种方法将它的所有元素都变成浮点数,但每次都失败了。

这个怎么样:

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)

这很棘手,因为数字的字符串表示不容易转换为浮点数,因此您可能必须手动解析它

这个怎么样?

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.])