How to Slice Numpy Arrays?
Numpy arrays can be sliced using the standard Python x[obj]
syntax.
import numpy as np
A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Basics
Basic operations with one dimensional array are similar to standard Python slicing operation.
a slice is constructed using:
[start:stop:step]
A[0:5]
array([0, 1, 2, 3, 4])
A[:5]
array([0, 1, 2, 3, 4])
# Using step
A[0:10:2]
array([0, 2, 4, 6, 8])
A[::2]
array([0, 2, 4, 6, 8])
A[-2:10]
array([8, 9])
A[0:-2]
array([0, 1, 2, 3, 4, 5, 6, 7])
## Multi Dimensional Array
# Example: three dimensional array:
x = np.array([[[1], [2], [3]], [[4], [5], [6]]])
x
array([[[1],
[2],
[3]],
[[4],
[5],
[6]]])
x.ndim
3
the shape
attribute returns a tuple that shows how many elements each dimension has
x.shape
(2, 3, 1)
In this case, the first dimension has two elements, the second dimension has 3 elements and the third dimension has one element
If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions.
x[1:2]
array([[[4],
[5],
[6]]])
Ellipsis ...
expands to the number of :
objects needed for the selection tuple to index all dimensions.
x[..., 0]
array([[1, 2, 3],
[4, 5, 6]])
x[0, ...]
array([[1],
[2],
[3]])
Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.
x[:, np.newaxis, :, :]
array([[[[1],
[2],
[3]]],
[[[4],
[5],
[6]]]])
## Multi-Dimensional Arrays: Extracting Columns
X = np.array([[1, 2, 3], [4, 5, 6]])
X
array([[1, 2, 3],
[4, 5, 6]])
Unlike lists and tuples, numpy arrays support multidimensional indexing for multidimensional arrays. That means that it is not necessary to separate each dimension’s index into its own set of square brackets.
Example:
The first element of the first dimension is [1, 2, 3]
, we select it using X[0]
X[0]
array([1, 2, 3])
Now, if we want to extract the second element (second dimension) from the first element of the first dimension, we use: X[0][1]
X[0][1]
2
numpy arrays support multidimensional indexing for multidimensional arrays. That means that it is not necessary to separate each dimension’s index into its own set of square brackets.
The comma, is used to separate dimensions in numpy.
This means that:
X[0][1]
is equivalent to X[0, 1]
X[0, 1]
2
This is useful for selecting matrix columns.
For example, if we need to select the first column, we use ,0
X[:, 0]
array([1, 4])
For selecting the second column, we use ,1
X[:, 1]
array([2, 5])
And for selecting the third column, we use ,2
X[:, 2]
array([3, 6])