ng150716
ng150716

Reputation: 2244

Append to Numpy Using a For Loop

I am working on a Python script that takes live streaming data and appends it to a numpy array. However I noticed that if I append to four different arrays one by one it works. For example:

openBidArray = np.append(openBidArray, bidPrice)
highBidArray = np.append(highBidArray, bidPrice)
lowBidArray = np.append(lowBidArray, bidPrice)
closeBidArray = np.append(closeBidArray, bidPrice)

However If I do the following it does not work:

arrays = ["openBidArray", "highBidArray", "lowBidArray", "closeBidArray"]

for array in arrays:
    array = np.append(array, bidPrice)

Any idea on why that is?

Upvotes: 1

Views: 7689

Answers (2)

kindall
kindall

Reputation: 184091

Do this instead:

arrays = [openBidArray, highBidArray, lowBidArray, closeBidArray]

In other words, your list should be a list of arrays, not a list of strings that coincidentally contain the names of arrays you happen to have defined.

Your next problem is that np.append() returns a copy of the array with the item appended, rather than appending in place. You store this result in array, but array will be assigned the next item from the list on the next iteration, and the modified array will be lost (except for the last one, of course, which will be in array at the end of the loop). So you will want to store each modified array back into the list. To do that, you need to know what slot it came from, which you can get using enumerate().

for i, array in enumerate(arrays):
    arrays[i] = np.append(array, bidPrice)

Now of course this doesn't update your original variables, openBidArray and so on. You could do this after the loop using unpacking:

openBidArray, highBidArray, lowBidArray, closeBidArray = arrays

But at some point it just makes more sense to store the arrays in a list (or a dictionary if you need to access them by name) to begin with and not use the separate variables.

N.B. if you used regular Python lists here instead of NumPy arrays, some of these issues would go away. append() on lists is an in-place operation, so you wouldn't have to store the modified array back into the list or unpack to the individual variables. It might be feasible to do all the appending with lists and then convert them to arrays afterward, if you really need NumPy functionality on them.

Upvotes: 2

Logan Byers
Logan Byers

Reputation: 1573

In your second example, you have strings, not np.array objects. You are trying to append a number(?) to a string.

The string "openBidArray" doesn't hold any link to an array called openBidArray.

Upvotes: 1

Related Questions