Skip to main content

12.5) Filling Up An Array


More often than not, you’ll want to create an array of a specific shape and fill it with some number, such as zero or one. You can use the functions zeros() and ones(). These functions create a new array; taking the array shape (as a tuple) as an argument and populating the new array with zeros and ones, respectively. A shape of two rows and three columns is written as the tuple (2,3). Here are some examples for you to try:

>>> print np.zeros((2,3))  # 2 rows 3 columns
[[ 0.  0.  0.]
 [ 0.  0.  0.]]
>>> print np.ones((2,3),dtype='i')
[[1 1 1]
 [1 1 1]]

NumPy has a NaN (Not a Number) value which you can access with:

>>> np.nan   # or np.NaN or np.NAN
nan

To initialise an array with NaN values (don’t forget to set the type):

>>> a = np.empty((3,3),dtype=’i’) # create an empty array of the right size
>>> a[:]=np.NaN           # fill the array with NaN
>>> a
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

Note that filling a NumPy array with None also returns an array of nan.