{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.\n", "\n", "We can initialize numpy arrays from nested Python lists, and access elements using square brackets:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "(3,)\n", "(1, 2, 3)\n", "[5 2 3]\n", "(2, 3)\n", "(1, 2, 4)\n" ] } ], "source": [ "a = np.array([1, 2, 3]) # Create a rank 1 array\n", "print(type(a)) # Prints \"\"\n", "print(a.shape) # Prints \"(3,)\"\n", "print(a[0], a[1], a[2]) # Prints \"1 2 3\"\n", "a[0] = 5 # Change an element of the array\n", "print(a) # Prints \"[5, 2, 3]\"\n", "\n", "b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array\n", "print(b.shape) # Prints \"(2, 3)\"\n", "print(b[0, 0], b[0, 1], b[1, 0]) # Prints \"1 2 4\"\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0. 0.]\n", " [ 0. 0.]]\n", "[[ 1. 1.]]\n", "[[7 7]\n", " [7 7]]\n", "[[ 1. 0.]\n", " [ 0. 1.]]\n", "[[ 0.55659276 0.14026954]\n", " [ 0.68578799 0.60177695]]\n" ] } ], "source": [ "a = np.zeros((2,2)) # Create an array of all zeros\n", "print(a) # Prints \"[[ 0. 0.]\n", " # [ 0. 0.]]\"\n", "\n", "b = np.ones((1,2)) # Create an array of all ones\n", "print(b) # Prints \"[[ 1. 1.]]\"\n", "\n", "c = np.full((2,2), 7) # Create a constant array\n", "print(c) # Prints \"[[ 7. 7.]\n", " # [ 7. 7.]]\"\n", "\n", "d = np.eye(2) # Create a 2x2 identity matrix\n", "print(d) # Prints \"[[ 1. 0.]\n", " # [ 0. 1.]]\"\n", "\n", "e = np.random.random((2,2)) # Create an array filled with random values\n", "print(e) # Might print \"[[ 0.91940167 0.08143941]\n", " # [ 0.68744134 0.87236687]]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Array indexing\n", "Numpy offers several ways to index into arrays.\n", "\n", "Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "77\n" ] } ], "source": [ "# Create the following rank 2 array with shape (3, 4)\n", "# [[ 1 2 3 4]\n", "# [ 5 6 7 8]\n", "# [ 9 10 11 12]]\n", "a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\n", "\n", "# Use slicing to pull out the subarray consisting of the first 2 rows\n", "# and columns 1 and 2; b is the following array of shape (2, 2):\n", "# [[2 3]\n", "# [6 7]]\n", "b = a[:2, 1:3]\n", "\n", "# A slice of an array is a view into the same data, so modifying it\n", "# will modify the original array.\n", "print(a[0, 1]) # Prints \"2\"\n", "b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]\n", "print(a[0, 1]) # Prints \"77\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(array([5, 6, 7, 8]), (4,))\n", "(array([[5, 6, 7, 8]]), (1, 4))\n", "(array([ 2, 6, 10]), (3,))\n", "(array([[ 2],\n", " [ 6],\n", " [10]]), (3, 1))\n" ] } ], "source": [ "# Create the following rank 2 array with shape (3, 4)\n", "# [[ 1 2 3 4]\n", "# [ 5 6 7 8]\n", "# [ 9 10 11 12]]\n", "a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\n", "\n", "# Two ways of accessing the data in the middle row of the array.\n", "# Mixing integer indexing with slices yields an array of lower rank,\n", "# while using only slices yields an array of the same rank as the\n", "# original array:\n", "row_r1 = a[1, :] # Rank 1 view of the second row of a\n", "row_r2 = a[1:2, :] # Rank 2 view of the second row of a\n", "print(row_r1, row_r1.shape) # Prints \"[5 6 7 8] (4,)\"\n", "print(row_r2, row_r2.shape) # Prints \"[[5 6 7 8]] (1, 4)\"\n", "\n", "# We can make the same distinction when accessing columns of an array:\n", "col_r1 = a[:, 1]\n", "col_r2 = a[:, 1:2]\n", "print(col_r1, col_r1.shape) # Prints \"[ 2 6 10] (3,)\"\n", "print(col_r2, col_r2.shape) # Prints \"[[ 2]\n", " # [ 6]\n", " # [10]] (3, 1)\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:\n", "\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 4 5]\n", "[1 4 5]\n", "[2 2]\n", "[2 2]\n" ] } ], "source": [ "a = np.array([[1,2], [3, 4], [5, 6]])\n", "\n", "# An example of integer array indexing.\n", "# The returned array will have shape (3,) and\n", "print(a[[0, 1, 2], [0, 1, 0]]) # Prints \"[1 4 5]\"\n", "\n", "# The above example of integer array indexing is equivalent to this:\n", "print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints \"[1 4 5]\"\n", "\n", "# When using integer array indexing, you can reuse the same\n", "# element from the source array:\n", "print(a[[0, 0], [1, 1]]) # Prints \"[2 2]\"\n", "\n", "# Equivalent to the previous integer array indexing example\n", "print(np.array([a[0, 1], a[0, 1]])) # Prints \"[2 2]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:\n", "\n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3]\n", " [ 4 5 6]\n", " [ 7 8 9]\n", " [10 11 12]]\n", "[ 1 6 7 11]\n", "[[11 2 3]\n", " [ 4 5 16]\n", " [17 8 9]\n", " [10 21 12]]\n" ] } ], "source": [ "# Create a new array from which we will select elements\n", "a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n", "\n", "print(a) # prints \"array([[ 1, 2, 3],\n", " # [ 4, 5, 6],\n", " # [ 7, 8, 9],\n", " # [10, 11, 12]])\"\n", "\n", "# Create an array of indices\n", "b = np.array([0, 2, 0, 1])\n", "\n", "# Select one element from each row of a using the indices in b\n", "print(a[np.arange(4), b]) # Prints \"[ 1 6 7 11]\"\n", "\n", "# Mutate one element from each row of a using the indices in b\n", "a[np.arange(4), b] += 10\n", "\n", "print(a) # prints \"array([[11, 2, 3],\n", " # [ 4, 5, 16],\n", " # [17, 8, 9],\n", " # [10, 21, 12]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:\n", "\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[False False]\n", " [ True True]\n", " [ True True]]\n", "[3 4 5 6]\n", "[3 4 5 6]\n" ] } ], "source": [ "a = np.array([[1,2], [3, 4], [5, 6]])\n", "\n", "bool_idx = (a > 2) # Find the elements of a that are bigger than 2;\n", " # this returns a numpy array of Booleans of the same\n", " # shape as a, where each slot of bool_idx tells\n", " # whether that element of a is > 2.\n", "\n", "print(bool_idx) # Prints \"[[False False]\n", " # [ True True]\n", " # [ True True]]\"\n", "\n", "# We use boolean array indexing to construct a rank 1 array\n", "# consisting of the elements of a corresponding to the True values\n", "# of bool_idx\n", "print(a[bool_idx]) # Prints \"[3 4 5 6]\"\n", "\n", "# We can do all of the above in a single concise statement:\n", "print(a[a > 2]) # Prints \"[3 4 5 6]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Array math\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 6. 8.]\n", " [ 10. 12.]]\n", "[[ 6. 8.]\n", " [ 10. 12.]]\n", "[[-4. -4.]\n", " [-4. -4.]]\n", "[[-4. -4.]\n", " [-4. -4.]]\n", "[[ 5. 12.]\n", " [ 21. 32.]]\n", "[[ 5. 12.]\n", " [ 21. 32.]]\n", "[[ 0.2 0.33333333]\n", " [ 0.42857143 0.5 ]]\n", "[[ 0.2 0.33333333]\n", " [ 0.42857143 0.5 ]]\n", "[[ 1. 1.41421356]\n", " [ 1.73205081 2. ]]\n" ] } ], "source": [ "x = np.array([[1,2],[3,4]], dtype=np.float64)\n", "y = np.array([[5,6],[7,8]], dtype=np.float64)\n", "\n", "# Elementwise sum; both produce the array\n", "# [[ 6.0 8.0]\n", "# [10.0 12.0]]\n", "print(x + y)\n", "print(np.add(x, y))\n", "\n", "# Elementwise difference; both produce the array\n", "# [[-4.0 -4.0]\n", "# [-4.0 -4.0]]\n", "print(x - y)\n", "print(np.subtract(x, y))\n", "\n", "# Elementwise product; both produce the array\n", "# [[ 5.0 12.0]\n", "# [21.0 32.0]]\n", "print(x * y)\n", "print(np.multiply(x, y))\n", "\n", "# Elementwise division; both produce the array\n", "# [[ 0.2 0.33333333]\n", "# [ 0.42857143 0.5 ]]\n", "print(x / y)\n", "print(np.divide(x, y))\n", "\n", "# Elementwise square root; produces the array\n", "# [[ 1. 1.41421356]\n", "# [ 1.73205081 2. ]]\n", "print(np.sqrt(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that unlike MATLAB, * is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:\n", "\n" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "219\n", "219\n", "[29 67]\n", "[29 67]\n", "[[19 22]\n", " [43 50]]\n", "[[19 22]\n", " [43 50]]\n" ] } ], "source": [ "x = np.array([[1,2],[3,4]])\n", "y = np.array([[5,6],[7,8]])\n", "\n", "v = np.array([9,10])\n", "w = np.array([11, 12])\n", "\n", "# Inner product of vectors; both produce 219\n", "print(v.dot(w))\n", "print(np.dot(v, w))\n", "\n", "# Matrix / vector product; both produce the rank 1 array [29 67]\n", "print(x.dot(v))\n", "print(np.dot(x, v))\n", "\n", "# Matrix / matrix product; both produce the rank 2 array\n", "# [[19 22]\n", "# [43 50]]\n", "print(x.dot(y))\n", "print(np.dot(x, y))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum:\n", "\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "[4 6]\n", "[3 7]\n" ] } ], "source": [ "x = np.array([[1,2],[3,4]])\n", "\n", "print(np.sum(x)) # Compute sum of all elements; prints \"10\"\n", "print(np.sum(x, axis=0)) # Compute sum of each column; prints \"[4 6]\"\n", "print(np.sum(x, axis=1)) # Compute sum of each row; prints \"[3 7]\"\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:\n", "\n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2]\n", " [3 4]]\n", "[[1 3]\n", " [2 4]]\n", "[1 2 3]\n", "[1 2 3]\n" ] } ], "source": [ "\n", "x = np.array([[1,2], [3,4]])\n", "print(x) # Prints \"[[1 2]\n", " # [3 4]]\"\n", "print(x.T) # Prints \"[[1 3]\n", " # [2 4]]\"\n", "\n", "# Note that taking the transpose of a rank 1 array does nothing:\n", "v = np.array([1,2,3])\n", "print(v) # Prints \"[1 2 3]\"\n", "print(v.T) # Prints \"[1 2 3]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Broadcasting\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 2 2 4]\n", " [ 5 5 7]\n", " [ 8 8 10]\n", " [11 11 13]]\n" ] } ], "source": [ "# We will add the vector v to each row of the matrix x,\n", "# storing the result in the matrix y\n", "x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n", "v = np.array([1, 0, 1])\n", "y = np.empty_like(x) # Create an empty matrix with the same shape as x\n", "\n", "# Add the vector v to each row of the matrix x with an explicit loop\n", "for i in range(4):\n", " y[i, :] = x[i, :] + v\n", "\n", "# Now y is the following\n", "# [[ 2 2 4]\n", "# [ 5 5 7]\n", "# [ 8 8 10]\n", "# [11 11 13]]\n", "print(y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }