Append to Numpy Using a For Loop
<p>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:</p>

<pre><code>openBidArray = np.append(openBidArray, bidPrice)
highBidArray = np.append(highBidArray, bidPrice)
lowBidArray = np.append(lowBidArray, bidPrice)
closeBidArray = np.append(closeBidArray, bidPrice)
</code></pre>

<p>However If I do the following it does not work:</p>

<pre><code>arrays = ["openBidArray", "highBidArray", "lowBidArray", "closeBidArray"]

for array in arrays:
    array = np.append(array, bidPrice)
</code></pre>

<p>Any idea on why that is?</p>

<p>Do this instead:</p>

<pre><code>arrays = [openBidArray, highBidArray, lowBidArray, closeBidArray]
</code></pre>

<p>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.</p>

<p>Your next problem is that <code>np.append()</code> returns a copy of the array with the item appended, rather than appending in place. You store this result in <code>array</code>, but <code>array</code> 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 <code>array</code> 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 <code>enumerate()</code>.</p>

<pre><code>for i, array in enumerate(arrays):
    arrays[i] = np.append(array, bidPrice)
</code></pre>

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

<pre><code>openBidArray, highBidArray, lowBidArray, closeBidArray = arrays
</code></pre>

<p>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.</p>

<p>N.B. if you used regular Python lists here instead of NumPy arrays, some of these issues would go away. <code>append()</code> 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.</p>

python arrays numpy