{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introducing Basic and Advanced Indexing\n", "\n", "Thus far we have seen that we can access the contents of a NumPy array by specifying an integer or slice-object as an index for each one of its dimensions. Indexing into and slicing along the dimensions of an array are known as basic indexing. NumPy also provides a sophisticated system of \"advanced indexing\", which permits us powerful means for accessing elements of an array that is flexible beyond specifying integers and slices along axes. For example, we can use advanced indexing to access all of the negative-valued elements from `x`.\n", "\n", "```python\n", "# demonstrating basic indexing and advanced indexing\n", ">>> import numpy as np\n", ">>> x = np.array([[ -5, 2, 0, -7],\n", "... [ -1, 9, 3, 8],\n", "... [ -3, -3, 4, 6]])\n", "\n", "# Access the column-1 of row-0 and row-2.\n", "# This is an example of basic indexing. \n", "# A \"view\" of the underlying data in `x`\n", "# is produced; no data is copied.\n", ">>> x[::2, 1]\n", "array([ 2, -3])\n", "\n", "# An example of advanced indexing.\n", "# Access all negative elements in `x`.\n", "# This produces a copy of the accessed data.\n", ">>> x[x < 0]\n", "array([-5, -7, -1, -3, -3])\n", "```\n", "\n", "We will see that, where basic indexing provides us with a *view* of the data within the array, without making a copy of it, advanced indexing requires that a copy of the accessed data be made. Here, we will define basic indexing and understand the nuances of working with views of arrays. The next section, then, is dedicated to understanding advanced indexing. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Indexing\n", "We begin this subsection by defining precisely what basic indexing is. Next, we will touch on each component of this definition, and lastly we will delve into the significance of basic indexing in the way it permits us to reference the underlying data of an array without copying it.\n", "\n", "