错误:TypeError:只能将长度为1的数组转换为Python标量

时间:2018-08-19 09:56:44

标签: python python-3.x numpy

我运行代码时

mi出现错误:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

我尝试安装numpy 1.11.0,但无法正常工作。如果y更改为int(),则是一个新错误:

这是代码:

# Load airfoil from file
def airfoil_from_file(fname, n=256):
    dat = np.loadtxt(fname, skiprows=1)
    eps=1e-8

    num1 = round(dat[0,0])
    num2 = round(dat[0,1])

    if num1>1: 
        xy = zeros((num1+num2-1,2))
        xy[:num1,:] = dat[1:1+num1,:][::-1,:]
        xy[num1:,:] = dat[2+num1:,:]
    else:
        xy=dat.copy()

第一个错误:

Traceback (most recent call last):
  File "compute.py", line 18, in <module>
    rx, ry = airfoil_from_file('clarky.dat', n=128)
  File "/home/david/Descargas/L04PanelMethod/geometry.py", line 29, in airfoil_from_file
    xy = zeros((num1+num2-1,2))
TypeError: 'numpy.float64' object cannot be interpreted as an integer

如果我更改为int():

def airfoil_from_file(fname, n=256):
    dat = int(np.loadtxt(fname, skiprows=1))
    eps=1e-8

新错误:

Traceback (most recent call last):
  File "compute.py", line 18, in <module>
    rx, ry = airfoil_from_file('clarky.dat', n=128)
  File "/home/david/Descargas/L04PanelMethod/geometry.py", line 22, in airfoil_from_file
    dat = int(np.loadtxt(fname, skiprows=1))
TypeError: only length-1 arrays can be converted to Python scalars

请帮助

1 个答案:

答案 0 :(得分:0)

将原始代码中的xy = zeros((num1+num2-1,2))更改为xy = zeros((int(num1+num2)-1,2))

仅舍入四舍五入,但不会转换为int。

num1 = round(dat[0,0])

num2 = round(dat[0,1])

根据您的情况舍入到最接近的浮点数,例如回合(12.4)= 12.0。