使用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
相关产品推荐
相关产品推荐

