data-science-ipython-notebooks/numpy/02.06-Boolean-Arrays-and-Masks.ipynb
2017-03-13 04:41:59 -04:00

1281 lines
40 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"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",
"< [Computation on Arrays: Broadcasting](02.05-Computation-on-arrays-broadcasting.ipynb) | [Contents](Index.ipynb) | [Fancy Indexing](02.07-Fancy-Indexing.ipynb) >"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Comparisons, Masks, and Boolean Logic"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This section covers the use of Boolean masks to examine and manipulate values within NumPy arrays.\n",
"Masking comes up when you want to extract, modify, count, or otherwise manipulate values in an array based on some criterion: for example, you might wish to count all values greater than a certain value, or perhaps remove all outliers that are above some threshold.\n",
"In NumPy, Boolean masking is often the most efficient way to accomplish these types of tasks."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: Counting Rainy Days\n",
"\n",
"Imagine you have a series of data that represents the amount of precipitation each day for a year in a given city.\n",
"For example, here we'll load the daily rainfall statistics for the city of Seattle in 2014, using Pandas (which is covered in more detail in [Chapter 3](03.00-Introduction-to-Pandas.ipynb)):"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(365,)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"\n",
"# use pandas to extract rainfall inches as a NumPy array\n",
"rainfall = pd.read_csv('data/Seattle2014.csv')['PRCP'].values\n",
"inches = rainfall / 254 # 1/10mm -> inches\n",
"inches.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The array contains 365 values, giving daily rainfall in inches from January 1 to December 31, 2014.\n",
"\n",
"As a first quick visualization, let's look at the histogram of rainy days, which was generated using Matplotlib (we will explore this tool more fully in [Chapter 4](04.00-Introduction-To-Matplotlib.ipynb)):"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"import seaborn; seaborn.set() # set plot styles"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAesAAAFVCAYAAADPM8ekAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAFJ1JREFUeJzt3W+MXWWh7/HftDOFzp9SL46JuWLHU2vkTwM61Ysh1r5o\nk1bI1QrFdmRKZTSWqLcyEaQIFhABFcO5CW1S5YWhvLA1QDQmJt6GVBLE2ENCCS00JzRQDhewBW1n\nT2lnoPu+OPeMIjD/3DPz7M7n86qz99O9n92nK9+91tqzdkO1Wq0GACjWjKmeAAAwPLEGgMKJNQAU\nTqwBoHBiDQCFE2sAKFzjcHe+8cYbueGGG/Liiy9mcHAw69evz/vf//587WtfS0dHR5JkzZo1WbFi\nRXbs2JHt27enqakp69evz5IlSyZh+gBw6msY7vesH3zwwezfv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2LI8++mhWr16d5D+vF/6b3/wmr7/+elatWpWNGzfmqquuSrVazapVq/K+9w3/xfFM\nrpHWr7e3N93d3TnttNPyqU99KosXL57iGfNOGhr+86s6bXv16Z3Wz7ZXtq1bt+bo0aPZsmVLNm/e\nnIaGhlx++eXj3v5cGxwACueiKABQOLEGgMKJNQAUTqwBoHBiDQCFE2sAKJxYA0Dh/h/uLOJdBEs5\nngAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x10b617a58>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.hist(inches, 40);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This histogram gives us a general idea of what the data looks like: despite its reputation, the vast majority of days in Seattle saw near zero measured rainfall in 2014.\n",
"But this doesn't do a good job of conveying some information we'd like to see: for example, how many rainy days were there in the year? What is the average precipitation on those rainy days? How many days were there with more than half an inch of rain?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Digging into the data\n",
"\n",
"One approach to this would be to answer these questions by hand: loop through the data, incrementing a counter each time we see values in some desired range.\n",
"For reasons discussed throughout this chapter, such an approach is very inefficient, both from the standpoint of time writing code and time computing the result.\n",
"We saw in [Computation on NumPy Arrays: Universal Functions](02.03-Computation-on-arrays-ufuncs.ipynb) that NumPy's ufuncs can be used in place of loops to do fast element-wise arithmetic operations on arrays; in the same way, we can use other ufuncs to do element-wise *comparisons* over arrays, and we can then manipulate the results to answer the questions we have.\n",
"We'll leave the data aside for right now, and discuss some general tools in NumPy to use *masking* to quickly answer these types of questions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparison Operators as ufuncs\n",
"\n",
"In [Computation on NumPy Arrays: Universal Functions](02.03-Computation-on-arrays-ufuncs.ipynb) we introduced ufuncs, and focused in particular on arithmetic operators. We saw that using ``+``, ``-``, ``*``, ``/``, and others on arrays leads to element-wise operations.\n",
"NumPy also implements comparison operators such as ``<`` (less than) and ``>`` (greater than) as element-wise ufuncs.\n",
"The result of these comparison operators is always an array with a Boolean data type.\n",
"All six of the standard comparison operations are available:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = np.array([1, 2, 3, 4, 5])"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([ True, True, False, False, False], dtype=bool)"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x < 3 # less than"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([False, False, False, True, True], dtype=bool)"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x > 3 # greater than"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([ True, True, True, False, False], dtype=bool)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x <= 3 # less than or equal"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([False, False, True, True, True], dtype=bool)"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x >= 3 # greater than or equal"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([ True, True, False, True, True], dtype=bool)"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x != 3 # not equal"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([False, False, True, False, False], dtype=bool)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x == 3 # equal"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is also possible to do an element-wise comparison of two arrays, and to include compound expressions:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([False, True, False, False, False], dtype=bool)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(2 * x) == (x ** 2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As in the case of arithmetic operators, the comparison operators are implemented as ufuncs in NumPy; for example, when you write ``x < 3``, internally NumPy uses ``np.less(x, 3)``.\n",
" A summary of the comparison operators and their equivalent ufunc is shown here:\n",
"\n",
"| Operator\t | Equivalent ufunc || Operator\t | Equivalent ufunc |\n",
"|---------------|---------------------||---------------|---------------------|\n",
"|``==`` |``np.equal`` ||``!=`` |``np.not_equal`` |\n",
"|``<`` |``np.less`` ||``<=`` |``np.less_equal`` |\n",
"|``>`` |``np.greater`` ||``>=`` |``np.greater_equal`` |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just as in the case of arithmetic ufuncs, these will work on arrays of any size and shape.\n",
"Here is a two-dimensional example:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[5, 0, 3, 3],\n",
" [7, 9, 3, 5],\n",
" [2, 4, 7, 6]])"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"rng = np.random.RandomState(0)\n",
"x = rng.randint(10, size=(3, 4))\n",
"x"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[ True, True, True, True],\n",
" [False, False, True, True],\n",
" [ True, True, False, False]], dtype=bool)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x < 6"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In each case, the result is a Boolean array, and NumPy provides a number of straightforward patterns for working with these Boolean results."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Working with Boolean Arrays\n",
"\n",
"Given a Boolean array, there are a host of useful operations you can do.\n",
"We'll work with ``x``, the two-dimensional array we created earlier."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[5 0 3 3]\n",
" [7 9 3 5]\n",
" [2 4 7 6]]\n"
]
}
],
"source": [
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Counting entries\n",
"\n",
"To count the number of ``True`` entries in a Boolean array, ``np.count_nonzero`` is useful:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# how many values less than 6?\n",
"np.count_nonzero(x < 6)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that there are eight array entries that are less than 6.\n",
"Another way to get at this information is to use ``np.sum``; in this case, ``False`` is interpreted as ``0``, and ``True`` is interpreted as ``1``:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.sum(x < 6)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The benefit of ``sum()`` is that like with other NumPy aggregation functions, this summation can be done along rows or columns as well:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([4, 2, 2])"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# how many values less than 6 in each row?\n",
"np.sum(x < 6, axis=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This counts the number of values less than 6 in each row of the matrix.\n",
"\n",
"If we're interested in quickly checking whether any or all the values are true, we can use (you guessed it) ``np.any`` or ``np.all``:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# are there any values greater than 8?\n",
"np.any(x > 8)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# are there any values less than zero?\n",
"np.any(x < 0)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# are all values less than 10?\n",
"np.all(x < 10)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# are all values equal to 6?\n",
"np.all(x == 6)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"``np.all`` and ``np.any`` can be used along particular axes as well. For example:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([ True, False, True], dtype=bool)"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# are all values in each row less than 4?\n",
"np.all(x < 8, axis=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here all the elements in the first and third rows are less than 8, while this is not the case for the second row.\n",
"\n",
"Finally, a quick warning: as mentioned in [Aggregations: Min, Max, and Everything In Between](02.04-Computation-on-arrays-aggregates.ipynb), Python has built-in ``sum()``, ``any()``, and ``all()`` functions. These have a different syntax than the NumPy versions, and in particular will fail or produce unintended results when used on multidimensional arrays. Be sure that you are using ``np.sum()``, ``np.any()``, and ``np.all()`` for these examples!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Boolean operators\n",
"\n",
"We've already seen how we might count, say, all days with rain less than four inches, or all days with rain greater than two inches.\n",
"But what if we want to know about all days with rain less than four inches and greater than one inch?\n",
"This is accomplished through Python's *bitwise logic operators*, ``&``, ``|``, ``^``, and ``~``.\n",
"Like with the standard arithmetic operators, NumPy overloads these as ufuncs which work element-wise on (usually Boolean) arrays.\n",
"\n",
"For example, we can address this sort of compound question as follows:"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"29"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.sum((inches > 0.5) & (inches < 1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So we see that there are 29 days with rainfall between 0.5 and 1.0 inches.\n",
"\n",
"Note that the parentheses here are importantbecause of operator precedence rules, with parentheses removed this expression would be evaluated as follows, which results in an error:\n",
"\n",
"``` python\n",
"inches > (0.5 & inches) < 1\n",
"```\n",
"\n",
"Using the equivalence of *A AND B* and *NOT (NOT A OR NOT B)* (which you may remember if you've taken an introductory logic course), we can compute the same result in a different manner:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"29"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.sum(~( (inches <= 0.5) | (inches >= 1) ))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Combining comparison operators and Boolean operators on arrays can lead to a wide range of efficient logical operations.\n",
"\n",
"The following table summarizes the bitwise Boolean operators and their equivalent ufuncs:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Operator\t | Equivalent ufunc || Operator\t | Equivalent ufunc |\n",
"|---------------|---------------------||---------------|---------------------|\n",
"|``&`` |``np.bitwise_and`` ||&#124; |``np.bitwise_or`` |\n",
"|``^`` |``np.bitwise_xor`` ||``~`` |``np.bitwise_not`` |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using these tools, we might start to answer the types of questions we have about our weather data.\n",
"Here are some examples of results we can compute when combining masking with aggregations:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number days without rain: 215\n",
"Number days with rain: 150\n",
"Days with more than 0.5 inches: 37\n",
"Rainy days with < 0.2 inches : 75\n"
]
}
],
"source": [
"print(\"Number days without rain: \", np.sum(inches == 0))\n",
"print(\"Number days with rain: \", np.sum(inches != 0))\n",
"print(\"Days with more than 0.5 inches:\", np.sum(inches > 0.5))\n",
"print(\"Rainy days with < 0.2 inches :\", np.sum((inches > 0) &\n",
" (inches < 0.2)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Boolean Arrays as Masks\n",
"\n",
"In the preceding section we looked at aggregates computed directly on Boolean arrays.\n",
"A more powerful pattern is to use Boolean arrays as masks, to select particular subsets of the data themselves.\n",
"Returning to our ``x`` array from before, suppose we want an array of all values in the array that are less than, say, 5:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[5, 0, 3, 3],\n",
" [7, 9, 3, 5],\n",
" [2, 4, 7, 6]])"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can obtain a Boolean array for this condition easily, as we've already seen:"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([[False, True, True, True],\n",
" [False, False, True, False],\n",
" [ True, True, False, False]], dtype=bool)"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x < 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now to *select* these values from the array, we can simply index on this Boolean array; this is known as a *masking* operation:"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 3, 3, 3, 2, 4])"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[x < 5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What is returned is a one-dimensional array filled with all the values that meet this condition; in other words, all the values in positions at which the mask array is ``True``.\n",
"\n",
"We are then free do operate on these values as we wish.\n",
"For example, we can compute some relevant statistics on our Seattle rain data:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Median precip on rainy days in 2014 (inches): 0.194881889764\n",
"Median precip on summer days in 2014 (inches): 0.0\n",
"Maximum precip on summer days in 2014 (inches): 0.850393700787\n",
"Median precip on non-summer rainy days (inches): 0.200787401575\n"
]
}
],
"source": [
"# construct a mask of all rainy days\n",
"rainy = (inches > 0)\n",
"\n",
"# construct a mask of all summer days (June 21st is the 172nd day)\n",
"days = np.arange(365)\n",
"summer = (days > 172) & (days < 262)\n",
"\n",
"print(\"Median precip on rainy days in 2014 (inches): \",\n",
" np.median(inches[rainy]))\n",
"print(\"Median precip on summer days in 2014 (inches): \",\n",
" np.median(inches[summer]))\n",
"print(\"Maximum precip on summer days in 2014 (inches): \",\n",
" np.max(inches[summer]))\n",
"print(\"Median precip on non-summer rainy days (inches):\",\n",
" np.median(inches[rainy & ~summer]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By combining Boolean operations, masking operations, and aggregates, we can very quickly answer these sorts of questions for our dataset."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Aside: Using the Keywords and/or Versus the Operators &/|\n",
"\n",
"One common point of confusion is the difference between the keywords ``and`` and ``or`` on one hand, and the operators ``&`` and ``|`` on the other hand.\n",
"When would you use one versus the other?\n",
"\n",
"The difference is this: ``and`` and ``or`` gauge the truth or falsehood of *entire object*, while ``&`` and ``|`` refer to *bits within each object*.\n",
"\n",
"When you use ``and`` or ``or``, it's equivalent to asking Python to treat the object as a single Boolean entity.\n",
"In Python, all nonzero integers will evaluate as True. Thus:"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(True, False)"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bool(42), bool(0)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bool(42 and 0)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bool(42 or 0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you use ``&`` and ``|`` on integers, the expression operates on the bits of the element, applying the *and* or the *or* to the individual bits making up the number:"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'0b101010'"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bin(42)"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'0b111011'"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bin(59)"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'0b101010'"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bin(42 & 59)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'0b111011'"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bin(42 | 59)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that the corresponding bits of the binary representation are compared in order to yield the result.\n",
"\n",
"When you have an array of Boolean values in NumPy, this can be thought of as a string of bits where ``1 = True`` and ``0 = False``, and the result of ``&`` and ``|`` operates similarly to above:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([ True, True, True, False, True, True], dtype=bool)"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A = np.array([1, 0, 1, 0, 1, 0], dtype=bool)\n",
"B = np.array([1, 1, 1, 0, 1, 1], dtype=bool)\n",
"A | B"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using ``or`` on these arrays will try to evaluate the truth or falsehood of the entire array object, which is not a well-defined value:"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "ValueError",
"evalue": "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-38-5d8e4f2e21c0>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mA\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mB\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
]
}
],
"source": [
"A or B"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarly, when doing a Boolean expression on a given array, you should use ``|`` or ``&`` rather than ``or`` or ``and``:"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([False, False, False, False, False, True, True, True, False, False], dtype=bool)"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = np.arange(10)\n",
"(x > 4) & (x < 8)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Trying to evaluate the truth or falsehood of the entire array will give the same ``ValueError`` we saw previously:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "ValueError",
"evalue": "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-40-3d24f1ffd63d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m8\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
]
}
],
"source": [
"(x > 4) and (x < 8)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So remember this: ``and`` and ``or`` perform a single Boolean evaluation on an entire object, while ``&`` and ``|`` perform multiple Boolean evaluations on the content (the individual bits or bytes) of an object.\n",
"For Boolean NumPy arrays, the latter is nearly always the desired operation."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!--NAVIGATION-->\n",
"< [Computation on Arrays: Broadcasting](02.05-Computation-on-arrays-broadcasting.ipynb) | [Contents](Index.ipynb) | [Fancy Indexing](02.07-Fancy-Indexing.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
}