简体   繁体   English

'numpy.ndarray' 对象没有属性 'append'

[英]'numpy.ndarray' object has no attribute 'append'

Sorry for the noob question but I am very new to Python.很抱歉这个菜鸟问题,但我是 Python 的新手。

I have a function which takes creates a numpy array and adds to it:我有一个函数需要创建一个 numpy 数组并添加到它:

def prices(open, index):
    gap_amount = 100
    prices_array = np.array([])
    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

        day_changed = vbt.utils.datetime_nb.day_changed_nb(index[i - 1], index[i])
        
        # if we have a new day
        if (day_changed):
            first_bar_of_day = i
            fist_open_price_of_day = open[first_bar_of_day]
            target_price = increaseByPercentage(fist_open_price_of_day, gap_amount)

        prices_array.append(target_price)

    return prices_array

And when I append prices_array.append(target_price) I get the following error:当我附加prices_array.append(target_price)时,出现以下错误:

AttributeError: 'numpy.ndarray' object has no attribute 'append'

What am I doing wrong here?我在这里做错了什么?

Numpy arrays do not behave like lists in Python. Numpy 数组的行为不像 Python 中的列表。 A major advantage of arrays is that they form a contiguous block in memory, allowing for much faster operations compared to python lists.数组的一个主要优点是它们在内存中形成一个连续的块,与 python 列表相比,允许更快的操作。 If you can predict the final size of your array you should initialise it with that size, ie np.zeros(shape=predicted_size) .如果您可以预测数组的最终大小,则应使用该大小对其进行初始化,即np.zeros(shape=predicted_size) And then assign the values using a counting index, eg:然后使用计数索引分配值,例如:

final_size = 100
some_array = np.zeros(shape=final_size)
for i in range(final_size):
  some_result = your_functions()
  some_array[i] = some_result
  i += 1

To solve this error, you can use add() to add a single hashable element or update() to insert an iterable into a set.要解决此错误,您可以使用 add() 添加单个可哈希元素或使用 update() 将可迭代对象插入集合。 Otherwise, you can convert the set to a list then call the append() method.否则,您可以将集合转换为列表,然后调用 append() 方法。

prices_array.add(target_price)

or要么

prices_array.update(target_price)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM