1 错误提示
在执行 Python3 程序时,错误提示 TypeError: only integer scalar arrays can be converted to a scalar index
,小编的报错代码片段位置如下:
ind = np.where(np.diff(R > 0)==True)[0]+1
if np.size(ind) >= 1:
ind = ind[0]
else:
L = np.nan
if method == 1:
T = np.trapz(R[:ind], tLag[:ind])
L = T * meanU
elif method == 2:
indThres = np.where(abs(tLag-tmax) == min(abs(tLag-tmax)))
indThres = min(indThres[0][0], ind)
x = tLag[:indThres]
y = R[:indThres]
# x = tLag
# y = R
popt, pcov = curve_fit(func, x, y)
R1 = np.array([func(i, popt) for i in tLag[:ind]]).T
报错代码:
R1 = np.array([func(i, popt) for i in tLag[:ind]]).T
具体报错内容
2 错误解释
类型错误:只有整数标量数组才能转换为标量索引。
这应该是最新版本的python、numpy的问题。版本升级,有些方法已经发生改变,使将单个元素数组作为标量进行索引成为一个错误。
下面例子,当 arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
就会报该错误(此时 arr1 为 List 类型),如果是数组,则不会报错。
import numpy as np
arr1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
batch = np.random.choice(3, 2)
arr1_batch1 = arr1[batch]
print(arr1_batch1)
3 问题分析、问题解决
ind = np.where(np.diff(R > 0)==True)[0]+1
Out[8]: array([], dtype=int64)
>>> ind
Out[2]: array([], dtype=int64)
将出错代码行修改为:
if np.size(ind) >= 1:
ind = ind[0]
else:
L = np.nan
当 L为nan的时候,就应该直接return了,而不是再继续往下进行了
if np.size(ind) >= 1:
ind = ind[0]
else:
L = np.nan
return L
修改后整体代码为:
ind = np.where(np.diff(R > 0)==True)[0]+1
if np.size(ind) >= 1:
ind = ind[0]
else:
L = np.nan
return L
if method == 1:
T = np.trapz(R[:ind], tLag[:ind])
L = T * meanU
elif method == 2:
indThres = np.where(abs(tLag-tmax) == min(abs(tLag-tmax)))
indThres = min(indThres[0][0], ind)
x = tLag[:indThres]
y = R[:indThres]
popt, pcov = curve_fit(func, x, y)
R1 = np.array([func(i, popt) for i in tLag[:ind]]).T