Home > Back-end >  'numpy.ndarray' object has no attribute 'append'
'numpy.ndarray' object has no attribute 'append'

Time:12-21

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?

CodePudding user response:

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, i.e. np.zeros(shape=predicted_size). And then assign the values using a counting index, e.g.:

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

CodePudding user response:

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)
  • Related