2

I have a numpy array and I want to add n elements with the same value until the length of the array reaches 100.

For example

my_array = numpy.array([3, 4, 5])

Note that I do not know the length of the array beforehand. It may be anything 3 <= x <= 100

I want to add (100 - x) more elements, all with the value 9. How can I do it?

2
  • Do you mean, you "cannot" have length of the array known? Commented Jan 21, 2019 at 2:45
  • Yes, the array is generated by another function. Commented Jan 21, 2019 at 2:47

3 Answers 3

5

There are two ways to approach this: concatenating arrays or assigning them.

You can use np.concatenate and generate an appropriately sized array:

my_array = # as you defined it
remainder = [9] * (100 - len(my_array))
remainder = np.array(remainder)
a100 = np.concatenate((my_array, remainder))

Alternatively, you can construct a np.full array, and then overwrite some of the values using slice notation:

a100 = numpy.full(100, 9)
my_array = # as you defined it
a100[0:len(my_array)] = my_array
Sign up to request clarification or add additional context in comments.

Comments

3

It's important to remember with numpy arrays, you can't add elements like you can with lists. So adding numbers to an array is not really the best thing to do.

Far better is to start with an array, and replace the elements with new data as it comes in. For example:

import numpy as np
MY_SPECIAL_NUMBER = 100
my_array = np.array[3, 4, 5]
my_new_array = np.ones(100) * MY_SPECIAL_NUMBER
my_new_array[:my_array.size] = my_array

my_new_array is now what you want.

Comments

0

If you "cannot" know the size of your mysterious array:

fillvalue=9
padding=numpy.ones(100)*fillvalue
newarray=numpy.append(myarray, padding)
newarray=newarray[:100]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.