0

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?

5
  • 1
    append() is a function of List not ndarray. define list in this way: prices_array=[] , then you can use append() function. Commented Dec 21, 2022 at 13:28
  • 1
    Maybe try np.append() function instead? Commented Dec 21, 2022 at 13:29
  • np.append() sorted it, thanks Commented Dec 21, 2022 at 13:33
  • Appending to a numpy array is very inefficient as it copies the array (plus the new element) each time you append to it. Commented Dec 21, 2022 at 13:36
  • I wrote something to help you and others on your learning journey Commented Dec 22, 2022 at 10:31

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant answer, thanks. Will mark it when the time allows
0

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)

1 Comment

If using a set values that appear more than once will not be tracked correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.