mirror of
https://github.com/donnemartin/data-science-ipython-notebooks.git
synced 2024-03-22 13:30:56 +08:00
930 lines
61 KiB
Python
930 lines
61 KiB
Python
|
{
|
|||
|
"cells": [
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"<!--BOOK_INFORMATION-->\n",
|
|||
|
"<img align=\"left\" style=\"padding-right:10px;\" src=\"figures/PDSH-cover-small.png\">\n",
|
|||
|
"*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).*\n",
|
|||
|
"\n",
|
|||
|
"*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*\n",
|
|||
|
"\n",
|
|||
|
"*No changes were made to the contents of this notebook from the original.*"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"<!--NAVIGATION-->\n",
|
|||
|
"< [Comparisons, Masks, and Boolean Logic](02.06-Boolean-Arrays-and-Masks.ipynb) | [Contents](Index.ipynb) | [Sorting Arrays](02.08-Sorting.ipynb) >"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"# Fancy Indexing"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"In the previous sections, we saw how to access and modify portions of arrays using simple indices (e.g., ``arr[0]``), slices (e.g., ``arr[:5]``), and Boolean masks (e.g., ``arr[arr > 0]``).\n",
|
|||
|
"In this section, we'll look at another style of array indexing, known as *fancy indexing*.\n",
|
|||
|
"Fancy indexing is like the simple indexing we've already seen, but we pass arrays of indices in place of single scalars.\n",
|
|||
|
"This allows us to very quickly access and modify complicated subsets of an array's values."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Exploring Fancy Indexing\n",
|
|||
|
"\n",
|
|||
|
"Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once.\n",
|
|||
|
"For example, consider the following array:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 1,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[51 92 14 71 60 20 82 86 74 74]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"import numpy as np\n",
|
|||
|
"rand = np.random.RandomState(42)\n",
|
|||
|
"\n",
|
|||
|
"x = rand.randint(100, size=10)\n",
|
|||
|
"print(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Suppose we want to access three different elements. We could do it like this:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 2,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"[71, 86, 14]"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 2,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"[x[3], x[7], x[2]]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Alternatively, we can pass a single list or array of indices to obtain the same result:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 3,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([71, 86, 60])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 3,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"ind = [3, 7, 4]\n",
|
|||
|
"x[ind]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"When using fancy indexing, the shape of the result reflects the shape of the *index arrays* rather than the shape of the *array being indexed*:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 4,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[71, 86],\n",
|
|||
|
" [60, 20]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 4,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"ind = np.array([[3, 7],\n",
|
|||
|
" [4, 5]])\n",
|
|||
|
"x[ind]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Fancy indexing also works in multiple dimensions. Consider the following array:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 5,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[ 0, 1, 2, 3],\n",
|
|||
|
" [ 4, 5, 6, 7],\n",
|
|||
|
" [ 8, 9, 10, 11]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 5,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"X = np.arange(12).reshape((3, 4))\n",
|
|||
|
"X"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Like with standard indexing, the first index refers to the row, and the second to the column:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 6,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([ 2, 5, 11])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 6,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"row = np.array([0, 1, 2])\n",
|
|||
|
"col = np.array([2, 1, 3])\n",
|
|||
|
"X[row, col]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Notice that the first value in the result is ``X[0, 2]``, the second is ``X[1, 1]``, and the third is ``X[2, 3]``.\n",
|
|||
|
"The pairing of indices in fancy indexing follows all the broadcasting rules that were mentioned in [Computation on Arrays: Broadcasting](02.05-Computation-on-arrays-broadcasting.ipynb).\n",
|
|||
|
"So, for example, if we combine a column vector and a row vector within the indices, we get a two-dimensional result:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 7,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[ 2, 1, 3],\n",
|
|||
|
" [ 6, 5, 7],\n",
|
|||
|
" [10, 9, 11]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 7,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"X[row[:, np.newaxis], col]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Here, each row value is matched with each column vector, exactly as we saw in broadcasting of arithmetic operations.\n",
|
|||
|
"For example:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 8,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[0, 0, 0],\n",
|
|||
|
" [2, 1, 3],\n",
|
|||
|
" [4, 2, 6]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 8,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"row[:, np.newaxis] * col"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"It is always important to remember with fancy indexing that the return value reflects the *broadcasted shape of the indices*, rather than the shape of the array being indexed."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Combined Indexing\n",
|
|||
|
"\n",
|
|||
|
"For even more powerful operations, fancy indexing can be combined with the other indexing schemes we've seen:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 9,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[[ 0 1 2 3]\n",
|
|||
|
" [ 4 5 6 7]\n",
|
|||
|
" [ 8 9 10 11]]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"print(X)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"We can combine fancy and simple indices:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 10,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([10, 8, 9])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 10,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"X[2, [2, 0, 1]]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"We can also combine fancy indexing with slicing:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 11,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[ 6, 4, 5],\n",
|
|||
|
" [10, 8, 9]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 11,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"X[1:, [2, 0, 1]]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"And we can combine fancy indexing with masking:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 12,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([[ 0, 2],\n",
|
|||
|
" [ 4, 6],\n",
|
|||
|
" [ 8, 10]])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 12,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"mask = np.array([1, 0, 1, 0], dtype=bool)\n",
|
|||
|
"X[row[:, np.newaxis], mask]"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"All of these indexing options combined lead to a very flexible set of operations for accessing and modifying array values."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Example: Selecting Random Points\n",
|
|||
|
"\n",
|
|||
|
"One common use of fancy indexing is the selection of subsets of rows from a matrix.\n",
|
|||
|
"For example, we might have an $N$ by $D$ matrix representing $N$ points in $D$ dimensions, such as the following points drawn from a two-dimensional normal distribution:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 13,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"(100, 2)"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 13,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"mean = [0, 0]\n",
|
|||
|
"cov = [[1, 2],\n",
|
|||
|
" [2, 5]]\n",
|
|||
|
"X = rand.multivariate_normal(mean, cov, 100)\n",
|
|||
|
"X.shape"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Using the plotting tools we will discuss in [Introduction to Matplotlib](04.00-Introduction-To-Matplotlib.ipynb), we can visualize these points as a scatter-plot:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 14,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAecAAAFVCAYAAADVDycqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X9wlNWh//HPYkz4FciGb7Rk2tnmOg3fP2z1CzJjtQyS\nSgqKF9Q0gIDWOmkro1WQJqJeUCk34/YOMh2Bi3CxGItQGbjBfi+iQoYp6tXUb0OldxBFZMS1GEgW\nSKSEkOf7xyaQxPzY3Zzd5+w+79cMM26ye55zkoyf5/x8fI7jOAIAANYY5HYFAABAV4QzAACWIZwB\nALAM4QwAgGUIZwAALEM4AwBgmQyThbW2tqqiokKff/65MjIytGzZMhUUFJi8BAAAac9oz3nv3r1q\na2vT5s2bNX/+fD377LMmiwcAwBOMhvO3v/1tXbhwQY7j6MyZM7r88stNFg8AgCcYHdYeNmyYjh07\npilT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u7nOg1kMNCehNPSJl42EV3yf7dJ+NnGwsv/+1LHEICIIVE\n5ldPSdopabj27v27GhvDRnt48Sy46n4MaMfDLnr7rI29VOayUw9zzgCsEJlv/S9JsyTdpnD4Vyov\nrzF6jXhCqvtnOh520dtnO8K8rm6GqqvvNt6GeDCXnXroOQOwQjBYpL1731A4nLgeXvcjPaMJqVgf\ndmFjL9WG+XTEhnAGYAW/P0cTJ16m6urYwjMW8YRUx2e6PuyiqtfPxnIDkKwhcE5LSz0sCHMRiyJo\nv1fb31vbP/nkqO64Y4c
|
|||
|
"text/plain": [
|
|||
|
"<matplotlib.figure.Figure at 0x10e332048>"
|
|||
|
]
|
|||
|
},
|
|||
|
"metadata": {},
|
|||
|
"output_type": "display_data"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"%matplotlib inline\n",
|
|||
|
"import matplotlib.pyplot as plt\n",
|
|||
|
"import seaborn; seaborn.set() # for plot styling\n",
|
|||
|
"\n",
|
|||
|
"plt.scatter(X[:, 0], X[:, 1]);"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Let's use fancy indexing to select 20 random points. We'll do this by first choosing 20 random indices with no repeats, and use these indices to select a portion of the original array:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 15,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([93, 45, 73, 81, 50, 10, 98, 94, 4, 64, 65, 89, 47, 84, 82, 80, 25,\n",
|
|||
|
" 90, 63, 20])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 15,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"indices = np.random.choice(X.shape[0], 20, replace=False)\n",
|
|||
|
"indices"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 16,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"(20, 2)"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 16,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"selection = X[indices] # fancy indexing here\n",
|
|||
|
"selection.shape"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Now to see which points were selected, let's over-plot large circles at the locations of the selected points:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 17,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAecAAAFVCAYAAADVDycqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl0U+edN/CvVsuWbXnFYPbVQAATGYLBFjtmD4QQCA1M\n2+k5mZnMdEmaJm2aN+mWciZzTpqZt0lP0rztZNKkpFCSAGELBowNMZvACRBMWIONMbbBsiUv0pXu\n+4fHAiHJWnwtXVvfzz+tru599Hts4p+eXSGKoggiIiKSDWW0AyAiIiJPTM5EREQyw+RMREQkM0zO\nREREMsPkTEREJDNMzkRERDKjlrIwQRDw/PPPo7q6Gmq1Gr/+9a8xfPhwKT+CiIioz5O05VxSUgKX\ny4VNmzbhqaeewu9+9zspiyciIooJkibnYcOGwel0QhRFNDc3Q6PRSFk8ERFRTJC0W1uv16Oqq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/72V3fX8L20Wg0WL56In/1sPR56aATS0lKRmpqKlJQUrFq1\nCosXL+1WYgbgXqLl7/W9rly5hLFjx6G0tCRgYgaAZctWwOFwoLz8827FSOFhtzYRUZDM5np3S9Vi\nASorq7By5aPYvftTqNUamEwzkZjY0SoSRRHHjx9DbW0Nxo4dj4KCQnc5Uq1p1usFWCyer32xWBqR\nnGzA8ePHMGvWHPf1rrrFFQoFsrMHoqbmhiSxUmiYnImIguSrparT6bB8+Uo4HA6UlR2C3W6HKIoQ\nRREPPmjEQw9N67F4jMY
|
|||
|
"text/plain": [
|
|||
|
"<matplotlib.figure.Figure at 0x118687240>"
|
|||
|
]
|
|||
|
},
|
|||
|
"metadata": {},
|
|||
|
"output_type": "display_data"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"plt.scatter(X[:, 0], X[:, 1], alpha=0.3)\n",
|
|||
|
"plt.scatter(selection[:, 0], selection[:, 1],\n",
|
|||
|
" facecolor='none', s=200);"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"This sort of strategy is often used to quickly partition datasets, as is often needed in train/test splitting for validation of statistical models (see [Hyperparameters and Model Validation](05.03-Hyperparameters-and-Model-Validation.ipynb)), and in sampling approaches to answering statistical questions."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Modifying Values with Fancy Indexing\n",
|
|||
|
"\n",
|
|||
|
"Just as fancy indexing can be used to access parts of an array, it can also be used to modify parts of an array.\n",
|
|||
|
"For example, imagine we have an array of indices and we'd like to set the corresponding items in an array to some value:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 18,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[ 0 99 99 3 99 5 6 7 99 9]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.arange(10)\n",
|
|||
|
"i = np.array([2, 1, 8, 4])\n",
|
|||
|
"x[i] = 99\n",
|
|||
|
"print(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"We can use any assignment-type operator for this. For example:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 19,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[ 0 89 89 3 89 5 6 7 89 9]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x[i] -= 10\n",
|
|||
|
"print(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Notice, though, that repeated indices with these operations can cause some potentially unexpected results. Consider the following:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 20,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[ 6. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.zeros(10)\n",
|
|||
|
"x[[0, 0]] = [4, 6]\n",
|
|||
|
"print(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Where did the 4 go? The result of this operation is to first assign ``x[0] = 4``, followed by ``x[0] = 6``.\n",
|
|||
|
"The result, of course, is that ``x[0]`` contains the value 6.\n",
|
|||
|
"\n",
|
|||
|
"Fair enough, but consider this operation:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 21,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"text/plain": [
|
|||
|
"array([ 6., 0., 1., 1., 1., 0., 0., 0., 0., 0.])"
|
|||
|
]
|
|||
|
},
|
|||
|
"execution_count": 21,
|
|||
|
"metadata": {},
|
|||
|
"output_type": "execute_result"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"i = [2, 3, 3, 4, 4, 4]\n",
|
|||
|
"x[i] += 1\n",
|
|||
|
"x"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"You might expect that ``x[3]`` would contain the value 2, and ``x[3]`` would contain the value 3, as this is how many times each index is repeated. Why is this not the case?\n",
|
|||
|
"Conceptually, this is because ``x[i] += 1`` is meant as a shorthand of ``x[i] = x[i] + 1``. ``x[i] + 1`` is evaluated, and then the result is assigned to the indices in x.\n",
|
|||
|
"With this in mind, it is not the augmentation that happens multiple times, but the assignment, which leads to the rather nonintuitive results.\n",
|
|||
|
"\n",
|
|||
|
"So what if you want the other behavior where the operation is repeated? For this, you can use the ``at()`` method of ufuncs (available since NumPy 1.8), and do the following:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 22,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"[ 0. 0. 1. 2. 3. 0. 0. 0. 0. 0.]\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.zeros(10)\n",
|
|||
|
"np.add.at(x, i, 1)\n",
|
|||
|
"print(x)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"The ``at()`` method does an in-place application of the given operator at the specified indices (here, ``i``) with the specified value (here, 1).\n",
|
|||
|
"Another method that is similar in spirit is the ``reduceat()`` method of ufuncs, which you can read about in the NumPy documentation."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"## Example: Binning Data\n",
|
|||
|
"\n",
|
|||
|
"You can use these ideas to efficiently bin data to create a histogram by hand.\n",
|
|||
|
"For example, imagine we have 1,000 values and would like to quickly find where they fall within an array of bins.\n",
|
|||
|
"We could compute it using ``ufunc.at`` like this:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 23,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [],
|
|||
|
"source": [
|
|||
|
"np.random.seed(42)\n",
|
|||
|
"x = np.random.randn(100)\n",
|
|||
|
"\n",
|
|||
|
"# compute a histogram by hand\n",
|
|||
|
"bins = np.linspace(-5, 5, 20)\n",
|
|||
|
"counts = np.zeros_like(bins)\n",
|
|||
|
"\n",
|
|||
|
"# find the appropriate bin for each x\n",
|
|||
|
"i = np.searchsorted(bins, x)\n",
|
|||
|
"\n",
|
|||
|
"# add 1 to each of these bins\n",
|
|||
|
"np.add.at(counts, i, 1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"The counts now reflect the number of points within each bin–in other words, a histogram:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 24,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"data": {
|
|||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeEAAAFVCAYAAADYEVdtAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAEydJREFUeJzt3X1s1WfZwPGrFNZtrMSOHBY3JyxjA5kLOiAhEwkhNEKI\n2VDGGAKijRmyJTgmIOt4GQ7YmBoT07oa4h6FKFkcyfaPLiFzW3AkVh9HsmnJM51xQQLFNNCCFih9\n/ljEl432tDv06svn8xdtz7nPxZ0D33Mf2h9lnZ2dnQEA9Llh2QMAwFAlwgCQRIQBIIkIA0ASEQaA\nJCIMAEmGd/XF8+fPxyOPPBJHjhyJc+fOxcqVK+PDH/5w3H///TFu3LiIiLjvvvti3rx5fTErAAwq\nZV39nPC+ffvi8OHDsWHDhjh58mTcfffd8cADD0RbW1usWLGiD8cEgMGnywj//e9/j87Ozrj66quj\npaUlFi1aFDNmzIg//elP0dHREWPHjo3a2tq4+uqr+3JmABgUuozwP7W1tcWqVavi3nvvjbNnz8aE\nCRNi0qRJ8fTTT8fJkydj/fr1fTErAAwq3X5j1tGjR+OLX/xiLFiwIObPnx9z5syJSZMmRUREdXV1\nNDU1dfsgrowJAO/V5TdmnThxImpqamLTpk0xffr0iIioqamJjRs3xu233x4HDx6M2267rdsHKSsr\ni+bm1tJMPMgVCpX2qgj2qXj2qjj2qTj2qXiFQmW3t+kywg0NDXHq1Kmor6+Purq6KCsriw0bNsT2\n7dtjxIgRUSgUYuvWrSUbGACGkqL+TbgUvHIqjleZxbFPxbNXxbFPxbFPxSvmJOxiHQCQRIQBIIkI\nA0ASEQaAJCIMAElEGACSiDAA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||
|
]
|
|||
|
},
|
|||
|
"metadata": {},
|
|||
|
"output_type": "display_data"
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"# plot the results\n",
|
|||
|
"plt.plot(bins, counts, linestyle='steps');"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Of course, it would be silly to have to do this each time you want to plot a histogram.\n",
|
|||
|
"This is why Matplotlib provides the ``plt.hist()`` routine, which does the same in a single line:\n",
|
|||
|
"\n",
|
|||
|
"```python\n",
|
|||
|
"plt.hist(x, bins, histtype='step');\n",
|
|||
|
"```\n",
|
|||
|
"\n",
|
|||
|
"This function will create a nearly identical plot to the one seen here.\n",
|
|||
|
"To compute the binning, ``matplotlib`` uses the ``np.histogram`` function, which does a very similar computation to what we did before. Let's compare the two here:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 25,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"NumPy routine:\n",
|
|||
|
"10000 loops, best of 3: 97.6 µs per loop\n",
|
|||
|
"Custom routine:\n",
|
|||
|
"10000 loops, best of 3: 19.5 µs per loop\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"print(\"NumPy routine:\")\n",
|
|||
|
"%timeit counts, edges = np.histogram(x, bins)\n",
|
|||
|
"\n",
|
|||
|
"print(\"Custom routine:\")\n",
|
|||
|
"%timeit np.add.at(counts, np.searchsorted(bins, x), 1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"Our own one-line algorithm is several times faster than the optimized algorithm in NumPy! How can this be?\n",
|
|||
|
"If you dig into the ``np.histogram`` source code (you can do this in IPython by typing ``np.histogram??``), you'll see that it's quite a bit more involved than the simple search-and-count that we've done; this is because NumPy's algorithm is more flexible, and particularly is designed for better performance when the number of data points becomes large:"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "code",
|
|||
|
"execution_count": 26,
|
|||
|
"metadata": {
|
|||
|
"collapsed": false
|
|||
|
},
|
|||
|
"outputs": [
|
|||
|
{
|
|||
|
"name": "stdout",
|
|||
|
"output_type": "stream",
|
|||
|
"text": [
|
|||
|
"NumPy routine:\n",
|
|||
|
"10 loops, best of 3: 68.7 ms per loop\n",
|
|||
|
"Custom routine:\n",
|
|||
|
"10 loops, best of 3: 135 ms per loop\n"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"source": [
|
|||
|
"x = np.random.randn(1000000)\n",
|
|||
|
"print(\"NumPy routine:\")\n",
|
|||
|
"%timeit counts, edges = np.histogram(x, bins)\n",
|
|||
|
"\n",
|
|||
|
"print(\"Custom routine:\")\n",
|
|||
|
"%timeit np.add.at(counts, np.searchsorted(bins, x), 1)"
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"What this comparison shows is that algorithmic efficiency is almost never a simple question. An algorithm efficient for large datasets will not always be the best choice for small datasets, and vice versa (see [Big-O Notation](02.08-Sorting.ipynb#Aside:-Big-O-Notation)).\n",
|
|||
|
"But the advantage of coding this algorithm yourself is that with an understanding of these basic methods, you could use these building blocks to extend this to do some very interesting custom behaviors.\n",
|
|||
|
"The key to efficiently using Python in data-intensive applications is knowing about general convenience routines like ``np.histogram`` and when they're appropriate, but also knowing how to make use of lower-level functionality when you need more pointed behavior."
|
|||
|
]
|
|||
|
},
|
|||
|
{
|
|||
|
"cell_type": "markdown",
|
|||
|
"metadata": {},
|
|||
|
"source": [
|
|||
|
"<!--NAVIGATION-->\n",
|
|||
|
"< [Comparisons, Masks, and Boolean Logic](02.06-Boolean-Arrays-and-Masks.ipynb) | [Contents](Index.ipynb) | [Sorting Arrays](02.08-Sorting.ipynb) >"
|
|||
|
]
|
|||
|
}
|
|||
|
],
|
|||
|
"metadata": {
|
|||
|
"anaconda-cloud": {},
|
|||
|
"kernelspec": {
|
|||
|
"display_name": "Python 3",
|
|||
|
"language": "python",
|
|||
|
"name": "python3"
|
|||
|
},
|
|||
|
"language_info": {
|
|||
|
"codemirror_mode": {
|
|||
|
"name": "ipython",
|
|||
|
"version": 3
|
|||
|
},
|
|||
|
"file_extension": ".py",
|
|||
|
"mimetype": "text/x-python",
|
|||
|
"name": "python",
|
|||
|
"nbconvert_exporter": "python",
|
|||
|
"pygments_lexer": "ipython3",
|
|||
|
"version": "3.4.3"
|
|||
|
}
|
|||
|
},
|
|||
|
"nbformat": 4,
|
|||
|
"nbformat_minor": 0
|
|||
|
}
|