Python informer

Improve your Python coding skills

Creating numpy arrays

In this section we will look at how to create numpy arrays. This article shows various ways to create arrays with constant content (such as all zeros), the next article shows how to create arrays with varying data content.

zeros function

The zeros function creates a new array containing zeros. For example:

import numpy as np

a1 = np.zeros(4)
print(a1)

This will create a1, one dimensional array of length 4. By default the array will contain data of type float64, ie a double float.

[ 0.  0.  0.  0.]

Creating zero arrays of different shape

The shape of an array specifies the number of dimensions and the size of the array in each dimension. For example a shape of (2, 3) specifies a 2 dimensional array consisting of 2 rows of 3 columns:

a2 = np.zeros((2, 3))
print(a2)

Here is the output:

[[ 0.  0.  0.]
 [ 0.  0.  0.]]

The shape of the array is often specified by a tuple eg (2, 3). Of course you can use a list, or any other sequence of integers (even another numpy array if you want to).

For one dimensional arrays, you can optionally use a single integer, rather than a tuple of one item - this is what we did when we created a1 above.

Setting the data type

By default, the array is created with a data type of float64. You can use the optional parameter dtype to specify a different data type. For a numpy array, all the elements must be the same type.

In the code below, a2_ints is an integer array. See the article on data types for a full list of data types:

a2_ints = np.zeros((2, 2), dtype=np.int32)
print(a2_ints)

This gives:

[[0 0]
 [0 0]]

zeros_like

The zeros_like function will create a new array of zeros that is the same shape and data type as the supplied array:

b2_ints = np.zeros_like(a2_ints)

b2_ints now contains a new 2 by 2 array of integer zeros.

ones

The ones function is exactly the same as zeros, except that it fills the array with value 1. For example:

o2 = np.ones((3, 2))
print(o2)

gives:

[[1. 1.]
 [1. 1.]
 [1. 1.]]

There is also a ones_like function that works in an analogous way to zeros_like.

empty

The empty function is also similar to zeros, except that it leaves the data array uninitialised. empty might be slightly faster than zeros, so it can be used if you are intending to immediately initialise the array in some other way.

Bear in mind that the uninitialised memory might not be random. It will just be whatever happens to be in the memory, so it might potentially contain user data left behind from the last time the memory was used.

There is, of course, a corresponding empty_like function.

full

The full function takes an extra parameter, the fill value, and uses that value to initialise the array elements:

f2 = np.full((2, 3), 7)
print(f2)

Giving:

[[ 7.  7.  7.]
 [ 7.  7.  7.]]

Again, there is also a full_like function, using our previous a2 array:

g2 = np.full_like(a2, 3)
print(g2)

giving

[[3. 3. 3.]
 [3. 3. 3.]]