Python如何读取数值数组并按区间分类返回对应文本数组?
代码问题及正确实现
原代码存在的问题
- 缺少numpy导入语句,
array()、np.nditer属于numpy库的功能,使用前需要先导入 - 变量名拼写错误:定义的数组变量是
values,调用函数时误写为value - 索引使用错误:遍历的时候
i是数组的元素值,直接用x[i]赋值相当于把元素值当下标用,会出现索引越界问题 - return 位置错误:return放在for循环内部,第一次循环执行完就会直接返回,不会处理数组的全部元素
- 类型不兼容:数值类型的numpy数组不能直接写入字符串,需要单独创建结果容器存储分类文本
正确实现方式
方式1:通用基础实现(不依赖numpy)
新手优先推荐这种写法,逻辑清晰易理解:
values = [702, 664, 817, 893, 768, 789, 637, 642, 619, 724] def classify_value(x): if 600 <= x <= 699: return 'Low' elif 700 <= x <= 799: return 'Med' else: return 'High' y = [classify_value(v) for v in values]
运行后 y 的输出为:['Med', 'Low', 'High', 'High', 'Med', 'Med', 'Low', 'Low', 'Low', 'Med']
方式2:基于原循环逻辑的修改版
如果你希望保留原本的循环写法思路,可以调整为:
import numpy as np values = np.array([702, 664, 817, 893, 768, 789, 637, 642, 619, 724]) def function(x): result = [] for i in x: if 600 <= i <= 699: result.append('Low') elif 700 <= i <= 799: result.append('Med') else: result.append('High') return result y = function(values)
方式3:numpy向量化实现(适合大规模数组)
如果需要处理数据量较大的numpy数组,推荐用向量化条件判断,执行效率远高于循环遍历:
import numpy as np values = np.array([702, 664, 817, 893, 768, 789, 637, 642, 619, 724]) y = np.where(values <= 699, 'Low', np.where(values <=799, 'Med', 'High'))
运行后得到的y是字符串类型的numpy数组,和原数组顺序一一对应。
内容的提问来源于stack exchange,提问作者jros112
相关产品推荐
相关产品推荐

