Fill a numpy array with the same number?

I know how to fill with zero in an array of 100 elements:

np.zeros(100) 

But what if I want to fill it 9?

+8
numpy
source share
4 answers

You can use:

 a = np.empty(100) a.fill(9) 

and also if you prefer cutting syntax:

 a[...] = 9 

np.empty same as np.ones , etc., but can be a little faster since it does not initialize the data.

In newer versions of numpy (1.8 or later) you also have:

 np.full(100, 9) 
+14
source share

If you just want to get the same value across the entire array, and you never want to change it, you can fool the step by making it equal to zero. That way, you just take the memory as one value. But you will get a numpy virtual array of any size and shape.

 >>> import numpy as np >>> from numpy.lib import stride_tricks >>> arr = np.array([10]) >>> stride_tricks.as_strided(arr, (10, ), (0, )) array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) 

But note that if you change any of the elements, all values ​​in the array will be changed.

+1
source share

This question was discussed earlier, see initializing the NumPy array (padding with identical values) , also for which the fastest method.

+1
source share

As far as I can see, there is no special function to fill the array using 9s. Thus, you must create an empty (i.e. uninitialized) array with np.empty(100) and fill it with 9 or others in the loop.

0
source share

All Articles