首页 > 解决方案 > 将一个 numpy 字符串数组更改为浮点数,但由于 +: 'float' 和 'str' 的操作数类型不受支持,无法获得其平均值或总和

问题描述

这是我拥有的具有 dtype=object 的数组

>>> a
array([25.0, 0.0, 0.0, ..., 0.0, 83.3333, 0.0], dtype=object)

我尝试使用该astype方法转换数组但出现错误:

>>> a.astype(float)
ValueError: could not convert string to float: 

我尝试像这样显式更改每个元素的 dtype:

for i in range(len(a)):
    try:
        a[i]=np.float(a[i])
    except:
        print(a[i])

它工作正常,没有打印任何内容。

然后我astype再次尝试了该方法

>>> a.astype(float)
ValueError: could not convert string to float: 

标签: arraysnumpypython-3.6

解决方案


推荐阅读