Next / Previous / Contents / Shipman's homepage

5.3. Two-dimensional arrays

To create a two-dimensional array (matrix), use np.array() as demonstrated above, but use a sequence of sequences to provide the values.

>>> d2 = np.array([(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)])
>>> print d2
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

To retrieve a value from a matrix M, use an expression of the form M[row, col] where row is the row position and col is the column position.

>>> print d2[0,2]
2
>>> print d2[2, 3]
11

You can use slicing to get one row or column. A slice operation has this general form:

M[rows, cols]

In this form, rows and cols may be either regular Python slice operations (such as 2:5 to select the third through fifth items), or they may be just “:” to select all the elements in that dimension.

In this example, we extract a 2×3 submatrix, containing rows 0 and 1, and columns 0, 1, and 2.

>>> print d2[0:2, 0:3]
[[0 1 2]
 [4 5 6]]

This example extracts all the rows, but only the first three columns.

>>> print d2[:,0:3]
[[ 0  1  2]
 [ 4  5  6]
 [ 8  9 10]]

In this example we select all the columns, but only the first two rows.

>>> print d2[0:2,:]
[[0 1 2 3]
 [4 5 6 7]]

You can use the np.zeros() function to create an empty matrix. The argument is a sequence (list or tuple) of the dimensions; we'll use a tuple this time.

>>> z2 = np.zeros((2,7))
>>> print z2
[[ 0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.]]