Appending to empty array in a for loop (python)

Tags: ,



How do I append values in an empty numpy array? I have an array of values that I want to perform a mathematical equation on and from those values I want to append it to a new empty array. What I have is:

qa = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])    

values_a = np.array([])
for n in qa:
    value = np.math.factorial(n + 19)/(np.math.factorial(n)*np.math.factorial(19))
    values_array = np.append(values_a, value)

However, it isn’t appending and not sure why?

Answer

You’re missing the array name, you’re using values_array instead of values_a. Here’s a code that works using your logic:

qa = np.arange(21)
values_a = np.array([])
for n in qa:
    value = np.math.factorial(n + 19)/(np.math.factorial(n)*np.math.factorial(19))
    values_a = np.append(values_a, value)

Nevertheless, as some comments say, it is not recommended to use numpy.append inside a loop, so you can use scipy.special.factorial instead. It allows calculating the factorial of the whole array element-wise:

from scipy.special import factorial
factorial(qa + 19)/(factorial(qa) * factorial(19))


Source: stackoverflow