1

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?

4
  • 2
    Check the variable names. Commented Feb 11, 2021 at 4:20
  • 1
    Using np.append in a loop is not a good idea. List append, or even a list comprehension is faster and easier to use right. Commented Feb 11, 2021 at 4:20
  • values_array = np.array(list(map(lambda n: np.math.factorial(n + 19)/(np.math.factorial(n)*np.math.factorial(19)), qa))) Commented Feb 11, 2021 at 4:22
  • As @hpaulj said, array are usually not good for dynamic problem where you increase the size of array one after another. IF YOU HAVE TO use NumPy array, then define its size first and add its element using index. Commented Feb 11, 2021 at 4:24

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1

You are assigning the result of np.append to values_array, but next time through your loop you are overwriting that assignment. Instead, you want to assign the results of np.append into values_a so that you are building up values_a each successive iteration:

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.