且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TypeError:只能使用NUMPY将长度为1的数组转换为Python标量

更新时间:2021-09-28 18:08:55

使用

Use numpy.sqrt rather than math.sqrt. numpy.sqrt expects a scalar or array as input, on the other hand math.sqrt can only handle scalars.

>>> import numpy as np
>>> import math
>>> a = np.arange(5)
>>> np.sqrt(a)
array([ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ])
#error
>>> math.sqrt(a)
Traceback (most recent call last):
  File "<ipython-input-78-c7d50051514f>", line 1, in <module>
    math.sqrt(a)
TypeError: only length-1 arrays can be converted to Python scalars

>>>