You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NumPy查找指定索引异常值报错TypeError,如何解决?

解决方法

错误根源在于你定义的array2是普通Python列表,而非numpy数组。np.where返回的索引是numpy数组类型,而Python列表不支持用数组作为索引,因此触发TypeError。

有两种简单的修复方式:

方式一:将array2转为numpy数组(推荐)

直接在定义时用np.array()包裹原始数据,让后续的numpy操作更顺畅:

import numpy as np
from scipy.stats import zscore

# 定义为numpy数组
array2 = np.array([26, 23, 26, 24, 15, 213, 19, 18, 17, 170, 20, 21, 16, 21, 19, 23, 21, 17, 19, 17, 28, 20, 27, 122, 23])
z_score_values = np.abs(zscore(array2))
outliers_index = np.where(z_score_values >= 2)[0]
outliers_list = array2[outliers_index]

print("异常值索引:", outliers_index)
print("异常值:", outliers_list)

方式二:保留列表类型,转换索引格式

如果需要维持array2的列表类型,把np.where返回的numpy索引数组转为普通Python列表后再索引:

import numpy as np
from scipy.stats import zscore

array2 = [26, 23, 26, 24, 15, 213, 19, 18, 17, 170, 20, 21, 16, 21, 19, 23, 21, 17, 19, 17, 28, 20, 27, 122, 23]
z_score_values = np.abs(zscore(array2))
outliers_index = np.where(z_score_values >= 2)[0]
# 将numpy索引转为Python列表,再逐个取值
outliers_list = [array2[i] for i in outliers_index.tolist()]

print("异常值索引:", outliers_index)
print("异常值:", outliers_list)

运行任意一种方式,都能正确输出异常值的索引和对应数值。

内容的提问来源于stack exchange,提问作者akshay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:24:28