Path: blob/master/notebooks/02.02-The-Basics-Of-NumPy-Arrays.ipynb
657 views
The Basics of NumPy Arrays
Data manipulation in Python is nearly synonymous with NumPy array manipulation: even newer tools like Pandas (Part 3) are built around the NumPy array. This chapter 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:
Attributes of arrays: Determining the size, shape, memory consumption, and data types of arrays
Indexing of arrays: Getting and setting the values of individual array elements
Slicing of arrays: Getting and setting smaller subarrays within a larger array
Reshaping of arrays: Changing the shape of a given array
Joining and splitting of arrays: Combining multiple arrays into one, and splitting one array into many
NumPy Array Attributes
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:
Each array has attributes including ndim
(the number of dimensions), shape
(the size of each dimension), size
(the total size of the array), and dtype
(the type of each element):
For more discussion of data types, see Understanding Data Types in Python.
Array Indexing: Accessing Single Elements
If you are familiar with Python's standard list indexing, indexing in NumPy will feel quite familiar. In a one-dimensional array, the value (counting from zero) can be accessed by specifying the desired index in square brackets, just as with Python lists:
To index from the end of the array, you can use negative indices:
In a multidimensional array, items can be accessed using a comma-separated (row, column)
tuple:
Values can also be modified using any of the preceding index notation:
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 into an integer array, the value will be silently truncated. Don't be caught unaware by this behavior!
Array Slicing: Accessing Subarrays
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:
If any of these are unspecified, they default to the values start=0
, stop=<size of dimension>
, step=1
. Let's look at some examples of accessing subarrays in one dimension and in multiple dimensions.
One-Dimensional Subarrays
Here are some examples of accessing elements in one-dimensional subarrays:
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:
Multidimensional Subarrays
Multidimensional slices work in the same way, with multiple slices separated by commas. For example:
Accessing array rows and columns
One commonly needed routine is accessing 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 (:
):
In the case of row access, the empty slice can be omitted for a more compact syntax:
Subarrays as No-Copy Views
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:
Let's extract a subarray from this:
Now if we modify this subarray, we'll see that the original array is changed! Observe:
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.
Creating Copies of Arrays
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:
If we now modify this subarray, the original array is not touched:
Reshaping of Arrays
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 grid, you can do the following:
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:
A convenient shorthand for this is to use np.newaxis
in the slicing syntax:
This is a pattern that we will utilize often throughout the remainder of the book.
Array Concatenation and Splitting
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 of 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 you can see here:
You can also concatenate more than two arrays at once:
And it can be used for two-dimensional arrays:
For working with arrays of mixed dimensions, it can be clearer to use the np.vstack
(vertical stack) and np.hstack
(horizontal stack) functions:
Similarly, for higher-dimensional arrays, np.dstack
will stack arrays along the third axis.
Splitting of Arrays
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:
Notice that N split points leads to N + 1 subarrays. The related functions np.hsplit
and np.vsplit
are similar:
Similarly, for higher-dimensional arrays, np.dsplit
will split arrays along the third axis.