This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.
The text is released under the CC-BY-NC-ND license, and code is released under the MIT license. If you find this content useful, please consider supporting the work by buying the book!
Data manipulation in Python is nearly synonymous with NumPy array manipulation: even newer tools like Pandas (Chapter 3) are built around the NumPy array. This section will present several examples of using NumPy array manipulation to access data and subarrays, and to split, reshape, and join the arrays. While the types of operations shown here may seem a bit dry and pedantic, they comprise the building blocks of many other examples used throughout the book. Get to know them well!
We'll cover a few categories of basic array manipulations here:
First let's discuss some useful array attributes. We'll start by defining random arrays of one, two, and three dimensions. We'll use NumPy's random number generator, which we will seed with a set value in order to ensure that the same random arrays are generated each time this code is run:
import numpy as np
rng = np.random.default_rng(seed=1701) # seed for reproducibility
x1 = rng.integers(10, size=6) # One-dimensional array
x2 = rng.integers(10, size=(3, 4)) # Two-dimensional array
x3 = rng.integers(10, size=(3, 4, 5)) # Three-dimensional array
Each array has attributes including ndim
(the number of dimensions), shape
(the size of each dimension), and size
(the total size of the array), and dtype
(the type of each element);
print("x3 ndim: ", x3.ndim)
print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)
print("dtype: ", x3.dtype)
x3 ndim: 3 x3 shape: (3, 4, 5) x3 size: 60 dtype: int64
For more discussion of dtype
, see Understanding Data Types in Python):
If you are familiar with Python's standard list indexing, indexing in NumPy will feel quite familiar. In a one-dimensional array, the $i^{th}$ value (counting from zero) can be accessed by specifying the desired index in square brackets, just as with Python lists:
x1
array([9, 4, 0, 3, 8, 6])
x1[0]
9
x1[4]
8
To index from the end of the array, you can use negative indices:
x1[-1]
6
x1[-2]
8
In a multi-dimensional array, items can be accessed using a comma-separated (row, column)
tuple:
x2
array([[3, 1, 3, 7], [4, 0, 2, 3], [0, 0, 6, 9]])
x2[0, 0]
3
x2[2, 0]
0
x2[2, -1]
9
Values can also be modified using any of the above index notation:
x2[0, 0] = 12
x2
array([[12, 1, 3, 7], [ 4, 0, 2, 3], [ 0, 0, 6, 9]])
Keep in mind that, unlike Python lists, NumPy arrays have a fixed type. This means, for example, that if you attempt to insert a floating-point value to an integer array, the value will be silently truncated. Don't be caught unaware by this behavior!
x1[0] = 3.14159 # this will be truncated!
x1
array([3, 4, 0, 3, 8, 6])
Just as we can use square brackets to access individual array elements, we can also use them to access subarrays with the slice notation, marked by the colon (:
) character.
The NumPy slicing syntax follows that of the standard Python list; to access a slice of an array x
, use this:
x[start:stop:step]
If any of these are unspecified, they default to the values start=0
, stop=
size of dimension
, step=1
.
We'll take a look at accessing sub-arrays in one dimension and in multiple dimensions.
x1
array([3, 4, 0, 3, 8, 6])
x1[:3] # first three elements
array([3, 4, 0])
x1[3:] # elements after index 3
array([3, 8, 6])
x1[1:4] # middle sub-array
array([4, 0, 3])
x1[::2] # every other element
array([3, 0, 8])
x1[1::2] # every other element, starting at index 1
array([4, 3, 6])
A potentially confusing case is when the step
value is negative.
In this case, the defaults for start
and stop
are swapped.
This becomes a convenient way to reverse an array:
x1[::-1] # all elements, reversed
array([6, 8, 3, 0, 4, 3])
x1[4::-2] # reversed every other from index 4
array([8, 0, 3])
Multi-dimensional slices work in the same way, with multiple slices separated by commas. For example:
x2
array([[12, 1, 3, 7], [ 4, 0, 2, 3], [ 0, 0, 6, 9]])
x2[:2, :3] # first two rows & three columns
array([[12, 1, 3], [ 4, 0, 2]])
x2[:3, ::2] # three rows, every other column
array([[12, 3], [ 4, 2], [ 0, 6]])
x2[::-1, ::-1] # all rows & columns, reversed
array([[ 9, 6, 0, 0], [ 3, 2, 0, 4], [ 7, 3, 1, 12]])
One commonly needed routine is accessing of single rows or columns of an array.
This can be done by combining indexing and slicing, using an empty slice marked by a single colon (:
):
x2[:, 0] # first column of x2
array([12, 4, 0])
x2[0, :] # first row of x2
array([12, 1, 3, 7])
In the case of row access, the empty slice can be omitted for a more compact syntax:
x2[0] # equivalent to x2[0, :]
array([12, 1, 3, 7])
Unlike Python list slices, NumPy array slices are returned as views rather than copies of the array data. Consider our two-dimensional array from before:
print(x2)
[[12 1 3 7] [ 4 0 2 3] [ 0 0 6 9]]
Let's extract a $2 \times 2$ subarray from this:
x2_sub = x2[:2, :2]
print(x2_sub)
[[12 1] [ 4 0]]
Now if we modify this subarray, we'll see that the original array is changed! Observe:
x2_sub[0, 0] = 99
print(x2_sub)
[[99 1] [ 4 0]]
print(x2)
[[99 1 3 7] [ 4 0 2 3] [ 0 0 6 9]]
Some users may find this surprising, but it can be advantageous: for example, when working with large datasets, we can access and process pieces of these datasets without the need to copy the underlying data buffer.
Despite the nice features of array views, it is sometimes useful to instead explicitly copy the data within an array or a subarray. This can be most easily done with the copy()
method:
x2_sub_copy = x2[:2, :2].copy()
print(x2_sub_copy)
[[99 1] [ 4 0]]
If we now modify this subarray, the original array is not touched:
x2_sub_copy[0, 0] = 42
print(x2_sub_copy)
[[42 1] [ 4 0]]
print(x2)
[[99 1 3 7] [ 4 0 2 3] [ 0 0 6 9]]
Another useful type of operation is reshaping of arrays, which can be done with the reshape
method.
For example, if you want to put the numbers 1 through 9 in a $3 \times 3$ grid, you can do the following:
grid = np.arange(1, 10).reshape(3, 3)
print(grid)
[[1 2 3] [4 5 6] [7 8 9]]
Note that for this to work, the size of the initial array must match the size of the reshaped array, and in most cases the reshape
method will return a no-copy view of the initial array.
A common reshaping operation is converting a one-dimensional array into a two-dimensional row or column matrix:
x = np.array([1, 2, 3])
x.reshape((1, 3)) # row vector via reshape
array([[1, 2, 3]])
x.reshape((3, 1)) # column vector via reshape
array([[1], [2], [3]])
A convenient shorthand for this is to use np.newaxis
within a slicing syntax:
x[np.newaxis, :] # row vector via newaxis
array([[1, 2, 3]])
x[:, np.newaxis] # column vector via newaxis
array([[1], [2], [3]])
This is a pattern that we will utilize often through the remainder of the book.
All of the preceding routines worked on single arrays. NumPy also provides tools to combine multiple arrays into one, and to conversely split a single array into multiple arrays.
Concatenation, or joining of two arrays in NumPy, is primarily accomplished using the routines np.concatenate
, np.vstack
, and np.hstack
.
np.concatenate
takes a tuple or list of arrays as its first argument, as we can see here:
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y])
array([1, 2, 3, 3, 2, 1])
You can also concatenate more than two arrays at once:
z = np.array([99, 99, 99])
print(np.concatenate([x, y, z]))
[ 1 2 3 3 2 1 99 99 99]
It can also be used for two-dimensional arrays:
grid = np.array([[1, 2, 3],
[4, 5, 6]])
# concatenate along the first axis
np.concatenate([grid, grid])
array([[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]])
# concatenate along the second axis (zero-indexed)
np.concatenate([grid, grid], axis=1)
array([[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]])
For working with arrays of mixed dimensions, it can be clearer to use the np.vstack
(vertical stack) and np.hstack
(horizontal stack) functions:
# vertically stack the arrays
np.vstack([x, grid])
array([[1, 2, 3], [1, 2, 3], [4, 5, 6]])
# horizontally stack the arrays
y = np.array([[99],
[99]])
np.hstack([grid, y])
array([[ 1, 2, 3, 99], [ 4, 5, 6, 99]])
Similary, for higher-dimensional arrays, np.dstack
will stack arrays along the third axis.
The opposite of concatenation is splitting, which is implemented by the functions np.split
, np.hsplit
, and np.vsplit
. For each of these, we can pass a list of indices giving the split points:
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 5])
print(x1, x2, x3)
[1 2 3] [99 99] [3 2 1]
Notice that N split-points, leads to N + 1 subarrays.
The related functions np.hsplit
and np.vsplit
are similar:
grid = np.arange(16).reshape((4, 4))
grid
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])
upper, lower = np.vsplit(grid, [2])
print(upper)
print(lower)
[[0 1 2 3] [4 5 6 7]] [[ 8 9 10 11] [12 13 14 15]]
left, right = np.hsplit(grid, [2])
print(left)
print(right)
[[ 0 1] [ 4 5] [ 8 9] [12 13]] [[ 2 3] [ 6 7] [10 11] [14 15]]
Similarly, for higher-dimensional arrays, np.dsplit
will split arrays along the third axis.