numpy.ndarray无append属性报错:我的代码哪里出错了?
问题分析与解决
错误原因
你遇到的AttributeError是因为numpy数组没有append实例方法——你用了Python列表的append语法,但prices_array是np.array()创建的numpy数组,不能这么调用。
两种修正方案
方案1:使用np.append()(适合小数据量)
把prices_array.append(target_price)改成:
prices_array = np.append(prices_array, target_price)
注意:np.append()每次都会创建新数组,数据量大时效率很低,不推荐在循环里频繁调用。
方案2:先通过列表收集数据,最后转numpy数组(推荐)
列表的追加操作效率更高,最后一次性转数组能避免频繁内存分配:
def prices(open, index): gap_amount = 100 # 初始化列表替代numpy数组 prices_list = [] index = index.vbt.to_ns() day = 0 target_price = 10000 first_bar_of_day = 0 for i in range(open.shape[0]): first_bar_of_day = 0 # 处理i=0的边界,避免index[i-1]越界 if i == 0: day_changed = False else: day_changed = vbt.utils.datetime_nb.day_changed_nb(index[i - 1], index[i]) if day_changed: first_bar_of_day = i # 修正拼写错误:fist → first first_open_price_of_day = open[first_bar_of_day] target_price = increaseByPercentage(first_open_price_of_day, gap_amount) prices_list.append(target_price) # 最后转成numpy数组返回 return np.array(prices_list)
额外注意点
- 原代码中
i=0时,index[i-1]会取到数组最后一个元素,导致日期判断错误,方案2已添加边界处理。 - 原代码里
fist_open_price_of_day是拼写错误,应为first_open_price_of_day,会引发变量未定义错误,已修正。
内容的提问来源于stack exchange,提问作者a7dc
相关产品推荐
相关产品推荐

