成功解决TypeError: only integer scalar arrays can be converted to a scalar index

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值