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:
JavaScript
x
7
1
qa = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
2
3
values_a = np.array([])
4
for n in qa:
5
value = np.math.factorial(n + 19)/(np.math.factorial(n)*np.math.factorial(19))
6
values_array = np.append(values_a, value)
7
However, it isn’t appending and not sure why?
Advertisement
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:
JavaScript
1
6
1
qa = np.arange(21)
2
values_a = np.array([])
3
for n in qa:
4
value = np.math.factorial(n + 19)/(np.math.factorial(n)*np.math.factorial(19))
5
values_a = np.append(values_a, value)
6
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:
JavaScript
1
3
1
from scipy.special import factorial
2
factorial(qa + 19)/(factorial(qa) * factorial(19))
3