{ "cells": [ { "cell_type": "raw", "metadata": { "raw_mimetype": "text/restructuredtext" }, "source": [ ".. meta::\n", " :description: Topic: Advanced indexing with numpy arrays, Difficulty: Hard, Category: Section\n", " :keywords: numpy array, integer array indexing, boolean array indexing, copy indexing, advanced" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Advanced Indexing\n", "\n", "We conclude our discussion of indexing into N-dimensional NumPy arrays by understanding advanced indexing. Unlike basic indexing, which allows us to access distinct elements and regular slices of an array, advanced indexing is significantly more flexible. For example, arrays of integers can be used to access arbitrary and even repeated entries from an array,\n", "\n", "```python\n", ">>> import numpy as np\n", "\n", ">>> x = np.array([[0, 1, 2],\n", "... [3, 4, 5],\n", "... [6, 7, 8]])\n", "\n", "# Construct the following 2D array\n", "# from the contents of `x`:\n", "#\n", "# [[x[0, 0], x[0, 1]],\n", "# [x[2, 2], x[2, 2]]]\n", ">>> rows = np.array([[0, 0], \n", "... [2, 2]])\n", "\n", ">>> cols = np.array([[0, 1], \n", "... [2, 2]])\n", "\n", ">>> x[rows, cols]\n", "array([[0, 1],\n", " [8, 8]])\n", "```\n", "\n", "Additionally, it permits the use of *boolean-valued* arrays as indices, \n", "\n", "```python\n", "# Use a boolean-valued array to access\n", "# the diagonal values of an array\n", "\n", "# Specify `True` wherever we want to access \n", "# the entry of `x`\n", ">>> bool_index = np.array([[ True, False, False],\n", "... [False, True, False],\n", "... [False, False, True]])\n", "\n", ">>> x[bool_index]\n", "array([0, 4, 8])\n", "```\n", "\n", "Unlike basic indexing, advanced indexing always produces a copy of the underlying data.\n", "```python\n", ">>> np.shares_memory(x, x[rows, cols])\n", "False\n", "\n", ">>> np.shares_memory(x, x[bool_index])\n", "False\n", "```\n", "The flexibility permitted by advanced indexing makes it a difficult topic to treat exhaustively without delving into somewhat terse and abstract notation. It is best to refer to [the official documentation](https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing) for such a treatment of the topic. Here, we will discuss the essential aspects of advanced indexing, with the aim of the discussion being both thorough and accessible." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "