Skip to content
Advertisement

Using a for loop to append to arrays in Numpy Python

The code below generates random integers within a given range within the for loop and I want to assign these values to the numpy arrays Values, up_value_one,up_value_two however the for loop below does not work. The Values of the Values, up_value_one,up_value_two are returned as empty arrays. How would I be able to use appender as the variable to append a,b,c to Values, up_value_one,up_value_two and update the arrays?

import numpy as np
from random import seed
from random import randint

# seed random number generator
seed(1)

def MXincrementedUpside():
    Values = np.array([])
    up_value_one= np.array([])
    up_value_two= np.array([])
    for x in range(3):
        a = randint(0, 20)
        b = randint(0, 10)
        c = randint(0, 15)
        for appender,vals in zip([Values, up_value_one,up_value_two],
                          [a,b,c]):
            appender = np.append(appender,vals)
    return {'Percentage Change': Values, 'Initial %':up_value_one,'Ending %':up_value_two}    
    
    
result =   MXincrementedUpside()
print(result)

Expected Output:

{'Percentage Change': array([1, 3,17], dtype=float64), 'Initial %': array([6,9,10], dtype=float64), 'Ending %': array([11,12,3], dtype=float64)}

Advertisement

Answer

You’re declaring a new appender in every iteration of the inside for loop, and because np.append doesn’t append in-place, nothing gets saved. I suggest you use list.append and then convert to np.array afterwards.

If you use list.append, your code requires minimal change. Simply change Values, up_value_one and up_value_two to lists and use list.append. Since it appends in-place, all these lists get updated in the loop:

def MXincrementedUpside():
    Values = []
    up_value_one = []
    up_value_two = []
    for x in range(3):
        a = randint(0, 20)
        b = randint(0, 10)
        c = randint(0, 15)
        for appender,vals in zip([Values, up_value_one,up_value_two],
                          [a,b,c]):
            appender.append(vals)
    return {'Percentage Change': np.array(Values), 'Initial %': np.array(up_value_one),'Ending %': np.array(up_value_two)} 

But if you insist on using np.append, below is one way of doing it:

def MXincrementedUpside():
    Values = np.array([])
    up_value_one= np.array([])
    up_value_two= np.array([])
    for x in range(3):
        Values = np.append(Values, randint(0, 20))
        up_value_one = np.append(up_value_one, randint(0, 10))
        up_value_two = np.append(up_value_two, randint(0, 15))
    return {'Percentage Change': Values, 'Initial %':up_value_one, 'Ending %':up_value_two}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement