简体   繁体   中英

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

Sorry for the noob question but I am very new to Python.

I have a function which takes creates a numpy array and adds to it:

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:

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

What am I doing wrong here?

Numpy arrays do not behave like lists in Python. A major advantage of arrays is that they form a contiguous block in memory, allowing for much faster operations compared to python lists. If you can predict the final size of your array you should initialise it with that size, ie 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. Otherwise, you can convert the set to a list then call the append() method.

prices_array.add(target_price)

or

prices_array.update(target_price)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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