{ "cells": [ { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2021-05-27T18:42:32.348446Z", "start_time": "2021-05-27T18:42:32.329894Z" } }, "source": [ "\n", "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/09_Python_NumPy_Module)**\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python NumPy Array: \n", "\n", "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", "Numpy array is a powerful N-dimensional array object which is in the form of rows and columns. We can initialize NumPy arrays from nested Python lists and access it elements." ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2021-05-27T18:42:42.296170Z", "start_time": "2021-05-27T18:42:42.277617Z" } }, "source": [ "## NumPy Array Types:\n", "\n", "
\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load in NumPy Library (remember to pip install numpy first)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:35.288206Z", "start_time": "2021-06-17T07:29:35.273564Z" } }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create a NumPy Array\n", "\n", "Simplest way to create an array in Numpy is to use Python List" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:36.473737Z", "start_time": "2021-06-17T07:29:36.458113Z" } }, "outputs": [ { "data": { "text/plain": [ "[2, 3, 4, 5]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myPythonList = [2,3,4,5]\n", "myPythonList" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To convert python list to a numpy array by using the object **`np.array`**." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:37.360439Z", "start_time": "2021-06-17T07:29:37.337985Z" } }, "outputs": [ { "data": { "text/plain": [ "array([2, 3, 4, 5])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numpy_array_from_list = np.array(myPythonList)\n", "numpy_array_from_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In practice, there is no need to declare a Python List. The operation can be combined." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:38.247143Z", "start_time": "2021-06-17T07:29:38.225663Z" } }, "outputs": [ { "data": { "text/plain": [ "array([2, 3, 4, 5])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myPythonList1 = np.array([2,3,4,5])\n", "myPythonList1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">**NOTE:** Numpy documentation states use of **`np.ndarray`** to create an array. However, this the recommended method\n", "\n", "You can also create a numpy array from a Tuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array basics " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can initialize numpy arrays from nested Python lists, and access elements using square brackets **`[]`**:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:39.026430Z", "start_time": "2021-06-17T07:29:39.017645Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 2 3]\n", "\n" ] } ], "source": [ "a = np.array([1,2,3]) # Create a 1D array\n", "print(a) \n", "print(type(a)) # Prints \"\"" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:39.307676Z", "start_time": "2021-06-17T07:29:39.285221Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[9. 8. 7.]\n", " [6. 5. 4.]]\n" ] } ], "source": [ "b = np.array([[9.0,8.0,7.0],[6.0,5.0,4.0]])\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:39.432674Z", "start_time": "2021-06-17T07:29:39.425841Z" } }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get Dimension\n", "a.ndim" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:39.604547Z", "start_time": "2021-06-17T07:29:39.583065Z" } }, "outputs": [ { "data": { "text/plain": [ "(2, 3)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get Shape\n", "b.shape" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:39.807665Z", "start_time": "2021-06-17T07:29:39.793022Z" } }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get Size\n", "a.itemsize" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:40.026413Z", "start_time": "2021-06-17T07:29:39.998096Z" } }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get Size\n", "b.itemsize" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:41.287622Z", "start_time": "2021-06-17T07:29:41.267121Z" } }, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get total size\n", "a.nbytes # a.nbytes = a.size * a.itemsize" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:41.568869Z", "start_time": "2021-06-17T07:29:41.551295Z" } }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get number of elements\n", "a.size" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Summary:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:42.252452Z", "start_time": "2021-06-17T07:29:42.228040Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 2 3]\n", "\n", "(3,)\n", "1 2 3\n", "[5 2 3]\n", "[[1 2 3]\n", " [4 5 6]]\n", "(2, 3)\n", "1 2 4\n" ] } ], "source": [ "a = np.array([1, 2, 3]) # Create a 1d array\n", "print(a)\n", "print(type(a)) # Prints \"\"\n", "print(a.shape) # Prints \"(3,)\"\n", "print(a[0], a[1], a[2]) # Indexing with 3 elements. 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 2d array\n", "print(b)\n", "print(b.shape) # Prints \"(2, 3)\"\n", "print(b[0, 0], b[0, 1], b[1, 0]) # Prints \"1 2 4\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy also provides many functions to create arrays:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:42.768068Z", "start_time": "2021-06-17T07:29:42.750496Z" }, "scrolled": true }, "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.73562437 0.24487723]\n", " [0.33931275 0.74965267]]\n" ] } ], "source": [ "import numpy as np\n", "\n", "a = np.zeros((2,2)) # numpy.zeros() or np.zeros Python function is used to create a matrix full of zeroes.\n", "print(a) # Prints \"[[ 0. 0.]\n", " # [ 0. 0.]]\"\n", "\n", "b = np.ones((1,2)) # np.ones() function is used to create a matrix full of 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": [ "You can read about other methods of array creation in this **[documentation](https://numpy.org/doc/stable/user/basics.creation.html#arrays-creation)**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array indexing\n", "\n", "Numpy offers several ways to index into arrays and accessing/changing specific elements, rows, columns, etc.\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": 15, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:45.257289Z", "start_time": "2021-06-17T07:29:45.242643Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3 4 5 6 7]\n", " [ 8 9 10 11 12 13 14]]\n" ] } ], "source": [ "# 2D array\n", "\n", "a = np.array([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]])\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:46.130323Z", "start_time": "2021-06-17T07:29:46.123487Z" } }, "outputs": [ { "data": { "text/plain": [ "13" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get a specific element [row, column]\n", "\n", "a[1, 5] # to select element '13' we need row 2 and element 6. Hence r=1, c=5 (index start from 0)\n", "\n", "# or a[1,-2]" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:46.333444Z", "start_time": "2021-06-17T07:29:46.319771Z" } }, "outputs": [ { "data": { "text/plain": [ "array([1, 2, 3, 4, 5, 6, 7])" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get a specific row \n", "a[0, :] # all columns" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:46.582460Z", "start_time": "2021-06-17T07:29:46.563911Z" } }, "outputs": [ { "data": { "text/plain": [ "array([ 3, 10])" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get a specific column\n", "a[:, 2] # all rows" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:46.738709Z", "start_time": "2021-06-17T07:29:46.727971Z" } }, "outputs": [ { "data": { "text/plain": [ "array([2, 4, 6])" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Getting a little more fancy [startindex:endindex:stepsize]\n", "a[0, 1:-1:2]" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:46.893978Z", "start_time": "2021-06-17T07:29:46.875428Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3 4 5 6 7]\n", " [ 8 9 10 11 12 20 14]]\n", "[[ 1 2 1 4 5 6 7]\n", " [ 8 9 2 11 12 20 14]]\n" ] } ], "source": [ "a[1,5] = 20\n", "print(a)\n", "\n", "a[:,2] = [1,2]\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:48.902735Z", "start_time": "2021-06-17T07:29:48.890046Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[[1 2]\n", " [3 4]]\n", "\n", " [[5 6]\n", " [7 8]]]\n" ] } ], "source": [ "# 3D example\n", "\n", "b = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:49.615615Z", "start_time": "2021-06-17T07:29:49.602434Z" } }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get specific element (work outside in)\n", "b[0,1,1]" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:50.542849Z", "start_time": "2021-06-17T07:29:50.195201Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[[1 2]\n", " [3 4]]\n", "\n", " [[5 6]\n", " [7 8]]]\n" ] }, { "ename": "ValueError", "evalue": "setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0mb\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m9\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m9\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m9\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m8\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m8\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mValueError\u001b[0m: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part." ] } ], "source": [ "# replace \n", "b[:,1,:]\n", "print(b)\n", "\n", "b[:,1,:] = [[9,9,9],[8,8]]\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Summary:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:54.495913Z", "start_time": "2021-06-17T07:29:54.482242Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3 4]\n", " [ 5 6 7 8]\n", " [ 9 10 11 12]]\n", "[[2 3]\n", " [6 7]]\n", "2\n", "77\n" ] } ], "source": [ "import numpy as np\n", "\n", "import numpy as np\n", "\n", "# 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", "print(a)\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", "print(b)\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. \n", "\n", ">**Note:** this is quite different from the way that MATLAB handles array slicing:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:57.018334Z", "start_time": "2021-06-17T07:29:57.002713Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3 4]\n", " [ 5 6 7 8]\n", " [ 9 10 11 12]]\n", "[5 6 7 8] (4,)\n", "[[5 6 7 8]] (1, 4)\n", "[ 2 6 10] (3,)\n", "[[ 2]\n", " [ 6]\n", " [10]] (3, 1)\n" ] } ], "source": [ "import numpy as np\n", "\n", "# 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", "print(a)\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\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:59.700421Z", "start_time": "2021-06-17T07:29:59.683822Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2]\n", " [3 4]\n", " [5 6]]\n", "[1 4 5]\n", "[1 4 5]\n", "[2 2]\n", "[2 2]\n" ] } ], "source": [ "import numpy as np\n", "\n", "a = np.array([[1,2], [3, 4], [5, 6]])\n", "print(a)\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:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:04.284332Z", "start_time": "2021-06-17T07:30:04.266761Z" }, "scrolled": true }, "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": [ "import numpy as np\n", "\n", "# 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": [ "### Quiz time" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:29:17.926182Z", "start_time": "2021-06-17T07:29:17.915441Z" } }, "outputs": [], "source": [ "# Generate matrix:\n", "\n", "### 1 2 3 4 5\n", "### 6 7 8 9 10\n", "### 11 12 13 14 15\n", "### 16 17 18 19 20\n", "### 21 22 23 24 25\n", "### 26 27 28 29 30\n", "\n", "# Acces \n", " 11 12\n", " 16 17\n", " \n", "# Acces \n", " 2\n", " 8\n", " 14\n", " 20\n", "\n", "# Acces \n", " 4 5\n", "\n", "\n", "\n", " 24 25\n", " 29 30" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Boolean array indexing\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:08.739828Z", "start_time": "2021-06-17T07:30:08.716397Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2]\n", " [3 4]\n", " [5 6]]\n", "[[False False]\n", " [ True True]\n", " [ True True]]\n", "[3 4 5 6]\n", "[3 4 5 6]\n" ] } ], "source": [ "import numpy as np\n", "\n", "a = np.array([[1,2], [3, 4], [5, 6]])\n", "print(a)\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": [ "For brevity we have left out a lot of details about numpy array indexing; if you want to know more about Array Indexing you should read this **[documentation](https://numpy.org/doc/stable/reference/arrays.indexing.html)**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array datatypes\n", "\n", "Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:11.875519Z", "start_time": "2021-06-17T07:30:11.858924Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 2 3]\n" ] } ], "source": [ "a = np.array([1,2,3], dtype='int32') # Create a 1D array with int32 type\n", "print(a) " ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:12.573753Z", "start_time": "2021-06-17T07:30:12.563011Z" } }, "outputs": [ { "data": { "text/plain": [ "dtype('int32')" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get Type\n", "a.dtype" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:13.244639Z", "start_time": "2021-06-17T07:30:13.235855Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[9. 8. 7.]\n", " [6. 5. 4.]]\n" ] }, { "data": { "text/plain": [ "dtype('float64')" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = np.array([[9.0,8.0,7.0],[6.0,5.0,4.0]])\n", "print(b)\n", "b.dtype" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can read all about numpy datatypes in this **[documentation](https://numpy.org/doc/stable/reference/arrays.dtypes.html)**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Summary" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:17.118117Z", "start_time": "2021-06-17T07:30:17.099563Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "int32\n", "float64\n", "int64\n" ] } ], "source": [ "import numpy as np\n", "\n", "x = np.array([1, 2]) # Let numpy choose the datatype\n", "print(x.dtype) # Prints \"int64\"\n", "\n", "x = np.array([1.0, 2.0]) # Let numpy choose the datatype\n", "print(x.dtype) # Prints \"float64\"\n", "\n", "x = np.array([1, 2], dtype=np.int64) # Force a particular datatype\n", "print(x.dtype) # Prints \"int64\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Numpy also provides many functions to create arrays:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:19.828030Z", "start_time": "2021-06-17T07:30:19.811431Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[0., 0., 0.],\n", " [0., 0., 0.]])" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# All 0s matrix\n", "np.zeros((2,3))" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:20.561416Z", "start_time": "2021-06-17T07:30:20.546771Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[[1, 1],\n", " [1, 1]],\n", "\n", " [[1, 1],\n", " [1, 1]],\n", "\n", " [[1, 1],\n", " [1, 1]],\n", "\n", " [[1, 1],\n", " [1, 1]]])" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# All 1s matrix\n", "np.ones((4,2,2), dtype='int32')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:21.122931Z", "start_time": "2021-06-17T07:30:21.114146Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[99, 99],\n", " [99, 99]])" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Any other number\n", "np.full((2,2), 99)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:23.866050Z", "start_time": "2021-06-17T07:30:23.850429Z" } }, "outputs": [ { "data": { "text/plain": [ "array([4, 4, 4])" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Any other number (full_like)\n", "np.full_like(a, 4)\n", "\n", "#or np.full(a.shape, 4)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:24.410965Z", "start_time": "2021-06-17T07:30:24.400225Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[0.41790066, 0.3047872 ],\n", " [0.40580783, 0.1946727 ],\n", " [0.7044376 , 0.31558553],\n", " [0.27878111, 0.62527265]])" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Random decimal numbers\n", "np.random.rand(4,2)\n", "\n", "#or\n", "#np.random.random_sample(a.shape)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:25.001289Z", "start_time": "2021-06-17T07:30:24.990548Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[ 3, -2, 3],\n", " [ 5, -2, -1],\n", " [ 2, -3, -4]])" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Random Integer values\n", "np.random.randint(-4,8, size=(3,3))" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:28.290297Z", "start_time": "2021-06-17T07:30:28.267840Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[1., 0., 0., 0., 0.],\n", " [0., 1., 0., 0., 0.],\n", " [0., 0., 1., 0., 0.],\n", " [0., 0., 0., 1., 0.],\n", " [0., 0., 0., 0., 1.]])" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# The identity matrix\n", "np.identity(5)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:29.100830Z", "start_time": "2021-06-17T07:30:29.081304Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [1 2 3]\n", " [1 2 3]]\n" ] } ], "source": [ "# Repeat an array\n", "arr = np.array([[1,2,3]])\n", "r1 = np.repeat(arr,3, axis=0)\n", "print(r1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Summary:" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:32.749210Z", "start_time": "2021-06-17T07:30:32.723824Z" } }, "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.67635086 0.51041159]\n", " [0.15725797 0.1589645 ]]\n" ] } ], "source": [ "import numpy as np\n", "\n", "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": [ "You can read about other methods of array creation in this **[documentation](https://numpy.org/doc/stable/user/basics.creation.html#arrays-creation)**." ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:35.942034Z", "start_time": "2021-06-17T07:30:35.932269Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 1. 1. 1. 1.]\n", " [1. 1. 1. 1. 1.]\n", " [1. 1. 1. 1. 1.]\n", " [1. 1. 1. 1. 1.]\n", " [1. 1. 1. 1. 1.]]\n", "[[0. 0. 0.]\n", " [0. 9. 0.]\n", " [0. 0. 0.]]\n", "[[1. 1. 1. 1. 1.]\n", " [1. 0. 0. 0. 1.]\n", " [1. 0. 9. 0. 1.]\n", " [1. 0. 0. 0. 1.]\n", " [1. 1. 1. 1. 1.]]\n" ] } ], "source": [ "#Generate matrix\n", "\n", "# 1 1 1 1 1\n", "# 1 0 0 0 1\n", "# 1 0 9 0 1\n", "# 1 1 1 1 1\n", "\n", "output = np.ones((5,5))\n", "print(output)\n", "\n", "z = np.zeros((3,3))\n", "z[1,1] = 9\n", "print(z)\n", "\n", "output[1:-1,1:-1] = z\n", "print(output)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Be careful when copying arrays!!!" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:38.856048Z", "start_time": "2021-06-17T07:30:38.847261Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[100 2 3]\n" ] } ], "source": [ "a = np.array([1,2,3])\n", "a\n", "b = a\n", "#b = a.copy()\n", "b[0] = 100\n", "\n", "print(a) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array math\n", "\n", "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": 44, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:39.649980Z", "start_time": "2021-06-17T07:30:39.643147Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1 2 3 4]\n" ] } ], "source": [ "a = np.array([1,2,3,4])\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:39.931227Z", "start_time": "2021-06-17T07:30:39.911698Z" } }, "outputs": [ { "data": { "text/plain": [ "array([3, 4, 5, 6])" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a + 2" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:40.134347Z", "start_time": "2021-06-17T07:30:40.113843Z" } }, "outputs": [ { "data": { "text/plain": [ "array([-1, 0, 1, 2])" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a - 2" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:40.320868Z", "start_time": "2021-06-17T07:30:40.301339Z" } }, "outputs": [ { "data": { "text/plain": [ "array([2, 4, 6, 8])" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a * 2" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:42.784206Z", "start_time": "2021-06-17T07:30:42.764678Z" } }, "outputs": [ { "data": { "text/plain": [ "array([0.5, 1. , 1.5, 2. ])" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a / 2" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:43.330095Z", "start_time": "2021-06-17T07:30:43.307639Z" } }, "outputs": [ { "data": { "text/plain": [ "array([2, 2, 4, 4])" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = np.array([1,0,1,0])\n", "a + b" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:43.813486Z", "start_time": "2021-06-17T07:30:43.795914Z" } }, "outputs": [ { "data": { "text/plain": [ "array([ 1, 4, 9, 16], dtype=int32)" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a ** 2" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:44.624997Z", "start_time": "2021-06-17T07:30:44.612306Z" } }, "outputs": [ { "data": { "text/plain": [ "array([ 0.54030231, -0.41614684, -0.9899925 , -0.65364362])" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Take the sin\n", "np.cos(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can find the full list of mathematical functions provided by numpy in this **[documentation](https://docs.scipy.org/doc/numpy/reference/routines.math.html)**." ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:47.539989Z", "start_time": "2021-06-17T07:30:47.515581Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 2.]\n", " [3. 4.]]\n", "[[5. 6.]\n", " [7. 8.]]\n", "[[ 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": [ "import numpy as np\n", "\n", "x = np.array([[1,2],[3,4]], dtype=np.float64)\n", "y = np.array([[5,6],[7,8]], dtype=np.float64)\n", "print(x)\n", "print(y)\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:" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:53.806979Z", "start_time": "2021-06-17T07:30:53.787451Z" } }, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### Dot product: product of two arrays\n", "\n", "f = np.array([1,2])\n", "g = np.array([4,5])\n", "### 1*4+2*5\n", "np.dot(f, g)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:56.260067Z", "start_time": "2021-06-17T07:30:56.244446Z" } }, "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": [ "import numpy as np\n", "\n", "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`**:" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:30:59.049089Z", "start_time": "2021-06-17T07:30:59.036393Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "[4 6]\n", "[3 7]\n" ] } ], "source": [ "import numpy as np\n", "\n", "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]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can find the full list of mathematical functions provided by numpy in this **[documentation](https://numpy.org/doc/stable/reference/routines.math.html)**." ] }, { "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:" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:02.994822Z", "start_time": "2021-06-17T07:31:02.984083Z" } }, "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": [ "import numpy as np\n", "\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": [ "Numpy provides many more functions for manipulating arrays; you can see the full list in the **[documentation](https://numpy.org/doc/stable/reference/routines.array-manipulation.html)**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Matrix Multiplication\n", "\n", "The Numpy **`matmul()`** function is used to return the matrix product of 2 arrays." ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:07.080697Z", "start_time": "2021-06-17T07:31:06.797499Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 1. 1.]\n", " [1. 1. 1.]]\n", "[[2 2]\n", " [2 2]\n", " [2 2]]\n" ] }, { "data": { "text/plain": [ "array([[6., 6.],\n", " [6., 6.]])" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = np.ones((2,3))\n", "print(a)\n", "\n", "b = np.full((3,2), 2)\n", "print(b)\n", "\n", "np.matmul(a,b) # matmul() function is used to return the matrix product of 2 arrays. " ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:10.073319Z", "start_time": "2021-06-17T07:31:10.052816Z" }, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "array([[19, 22],\n", " [43, 50]])" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### Matmul: matruc product of two arrays\n", "\n", "h = [[1,2],[3,4]] \n", "i = [[5,6],[7,8]] \n", "### 1*5+2*7 = 19\n", "np.matmul(h, i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Determinant\n", "\n", "Last but not least, if you need to compute the determinant, you can use **`np.linalg.det()`**. Note that numpy takes care of the dimension." ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:17.042936Z", "start_time": "2021-06-17T07:31:16.812471Z" } }, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Find the determinant\n", "\n", "c = np.identity(3)\n", "np.linalg.det(c)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:18.048286Z", "start_time": "2021-06-17T07:31:18.029738Z" } }, "outputs": [ { "data": { "text/plain": [ "-1.999999999999999" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "## Determinant 2*2 matrix\n", "\n", "5*8-7*6\n", "np.linalg.det(i)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Reference docs (https://docs.scipy.org/doc/numpy/reference/routines.linalg.html)\n", "\n", "# Determinant\n", "# Trace\n", "# Singular Vector Decomposition\n", "# Eigenvalues\n", "# Matrix Norm\n", "# Inverse\n", "# Etc..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Statistics\n", "\n", "NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc from the given elements in the array. The functions are explained as follows −" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy is equipped with the robust statistical function as listed below:\n", "\n", "| Function | Numpy |\n", "|:----: |:---- |\n", "| **`Min`** | **np.min()** | \n", "| **`Max`** | **np.max()** | \n", "| **`Mean`** | **np.mean()** | \n", "| **`Median`** | **np.median()** | \n", "| **`Standard deviation`** | **np.std()** | " ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:28.035913Z", "start_time": "2021-06-17T07:31:27.989042Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4.97560824 4.60947025 5.94484723 4.61372571 4.83980962 5.53527676\n", " 5.61889842 5.28103983 4.98568983 5.07159481]\n" ] } ], "source": [ "# Consider the following Array\n", "\n", "import numpy as np\n", "\n", "normal_array = np.random.normal(5, 0.5, 10)\n", "print(normal_array)\t" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:29.967524Z", "start_time": "2021-06-17T07:31:29.901120Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.609470247251966\n", "5.94484722747857\n", "5.147596068328039\n", "5.028642318227554\n", "0.41913457995913717\n" ] } ], "source": [ "# Example:Statistical function\n", "\n", "### Min \n", "print(np.min(normal_array))\n", "\n", "### Max \n", "print(np.max(normal_array))\n", "\n", "### Mean \n", "print(np.mean(normal_array))\n", "\n", "### Median\n", "print(np.median(normal_array))\n", "\n", "### Sd\n", "print(np.std(normal_array))" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:33.671560Z", "start_time": "2021-06-17T07:31:33.652033Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[1, 2, 3],\n", " [4, 5, 6]])" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stats = np.array([[1,2,3],[4,5,6]])\n", "stats" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:34.401041Z", "start_time": "2021-06-17T07:31:34.383468Z" } }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.min(stats)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:35.149076Z", "start_time": "2021-06-17T07:31:35.140290Z" } }, "outputs": [ { "data": { "text/plain": [ "array([3, 6])" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.max(stats, axis=1)" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:35.802877Z", "start_time": "2021-06-17T07:31:35.781392Z" } }, "outputs": [ { "data": { "text/plain": [ "array([5, 7, 9])" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.sum(stats, axis=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Broadcasting\n", "\n", "Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.\n", "\n", "For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:38.449312Z", "start_time": "2021-06-17T07:31:38.428808Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 2 2 4]\n", " [ 5 5 7]\n", " [ 8 8 10]\n", " [11 11 13]]\n" ] } ], "source": [ "import numpy as np\n", "\n", "# 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": "markdown", "metadata": {}, "source": [ "This works; however when the matrix **`x`** is very large, computing an explicit loop in Python could be slow. Note that adding the vector **`v`** to each row of the matrix **`x`** is equivalent to forming a matrix **`vv`** by stacking multiple copies of **`v`** vertically, then performing elementwise summation of **`x`** and **`vv`**. We could implement this approach like this:" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:41.488324Z", "start_time": "2021-06-17T07:31:41.464889Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 0 1]\n", " [1 0 1]\n", " [1 0 1]\n", " [1 0 1]]\n", "[[ 2 2 4]\n", " [ 5 5 7]\n", " [ 8 8 10]\n", " [11 11 13]]\n" ] } ], "source": [ "import numpy as np\n", "\n", "# 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", "vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other\n", "print(vv) # Prints \"[[1 0 1]\n", " # [1 0 1]\n", " # [1 0 1]\n", " # [1 0 1]]\"\n", "y = x + vv # Add x and vv elementwise\n", "print(y) # Prints \"[[ 2 2 4\n", " # [ 5 5 7]\n", " # [ 8 8 10]\n", " # [11 11 13]]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy broadcasting allows us to perform this computation without actually creating multiple copies of **`v`**. Consider this version, using broadcasting:" ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:44.760242Z", "start_time": "2021-06-17T07:31:44.749501Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 2 2 4]\n", " [ 5 5 7]\n", " [ 8 8 10]\n", " [11 11 13]]\n" ] } ], "source": [ "import numpy as np\n", "\n", "# 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 = x + v # Add v to each row of x using broadcasting\n", "print(y) # Prints \"[[ 2 2 4]\n", " # [ 5 5 7]\n", " # [ 8 8 10]\n", " # [11 11 13]]\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Explanation:** \n", "\n", "The line **`y = x + v`** works even though **`x`** has shape **(4, 3)** and **`v`** has shape **(3,)** due to broadcasting; this line works as if **`v`** actually had shape **(4, 3)**, where each row was a copy of **`v`**, and the sum was performed elementwise." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Broadcasting two arrays together follows these rules:\n", "\n", "* If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.\n", "\n", "\n", "* The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.\n", "\n", "\n", "* The arrays can be broadcast together if they are compatible in all dimensions.\n", "\n", "\n", "* After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.\n", "\n", "\n", "* In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension\n", "\n", "If this explanation does not make sense, try reading the explanation from this **[documentation](https://numpy.org/doc/stable/user/basics.broadcasting.html)** or this **[explanation](http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc)**.\n", "\n", "Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in this **[documentation](https://numpy.org/doc/stable/reference/ufuncs.html#available-ufuncs)**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are some applications of broadcasting:" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:50.983768Z", "start_time": "2021-06-17T07:31:50.958381Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 4 5]\n", " [ 8 10]\n", " [12 15]]\n", "[[2 4 6]\n", " [5 7 9]]\n", "[[ 5 6 7]\n", " [ 9 10 11]]\n", "[[ 5 6 7]\n", " [ 9 10 11]]\n", "[[ 2 4 6]\n", " [ 8 10 12]]\n" ] } ], "source": [ "import numpy as np\n", "\n", "# Compute outer product of vectors\n", "v = np.array([1,2,3]) # v has shape (3,)\n", "w = np.array([4,5]) # w has shape (2,)\n", "# To compute an outer product, we first reshape v to be a column\n", "# vector of shape (3, 1); we can then broadcast it against w to yield\n", "# an output of shape (3, 2), which is the outer product of v and w:\n", "# [[ 4 5]\n", "# [ 8 10]\n", "# [12 15]]\n", "print(np.reshape(v, (3, 1)) * w)\n", "\n", "# Add a vector to each row of a matrix\n", "x = np.array([[1,2,3], [4,5,6]])\n", "# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),\n", "# giving the following matrix:\n", "# [[2 4 6]\n", "# [5 7 9]]\n", "print(x + v)\n", "\n", "# Add a vector to each column of a matrix\n", "# x has shape (2, 3) and w has shape (2,).\n", "# If we transpose x then it has shape (3, 2) and can be broadcast\n", "# against w to yield a result of shape (3, 2); transposing this result\n", "# yields the final result of shape (2, 3) which is the matrix x with\n", "# the vector w added to each column. Gives the following matrix:\n", "# [[ 5 6 7]\n", "# [ 9 10 11]]\n", "print((x.T + w).T)\n", "# Another solution is to reshape w to be a column vector of shape (2, 1);\n", "# we can then broadcast it directly against x to produce the same\n", "# output.\n", "print(x + np.reshape(w, (2, 1)))\n", "\n", "# Multiply a matrix by a constant:\n", "# x has shape (2, 3). Numpy treats scalars as arrays of shape ();\n", "# these can be broadcast together to shape (2, 3), producing the\n", "# following array:\n", "# [[ 2 4 6]\n", "# [ 8 10 12]]\n", "print(x * 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arrays reorganizing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `asarray()`\n", "\n", "The **`asarray()`** function is used when you want to convert an input to an array. The input could be a lists, tuple, ndarray, etc.\n", "\n", "**Syntax:**\n", "```python\n", "numpy.asarray(data, dtype=None, order=None)[source]\n", "```\n", "\n", "* **`data`**: Data that you want to convert to an array\n", "\n", "* **`dtype`**: This is an optional argument. If not specified, the data type is inferred from the input data\n", "\n", "* **`Order`**: Default is **`C`** which is an essential row style. Other option is **`F`** (Fortan-style)" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:55.332810Z", "start_time": "2021-06-17T07:31:55.317191Z" } }, "outputs": [], "source": [ "# Consider the following 2-D matrix with four rows and four columns filled by 1\n", "\n", "import numpy as np\n", "\n", "a = np.matrix(np.ones((4,4)))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to change the value of the matrix, you cannot. The reason is, it is not possible to change a copy." ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:57.951907Z", "start_time": "2021-06-17T07:31:57.936287Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 1. 1. 1.]\n", " [1. 1. 1. 1.]\n", " [1. 1. 1. 1.]\n", " [1. 1. 1. 1.]]\n" ] } ], "source": [ "np.array(a)[2]=3\n", "print(a) # value won't change in result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Matrix is immutable. You can use asarray if you want to add modification in the original array. Let's see if any change occurs when you want to change the value of the third rows with the value 2" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:31:59.491922Z", "start_time": "2021-06-17T07:31:59.486062Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 1. 1. 1.]\n", " [1. 1. 1. 1.]\n", " [2. 2. 2. 2.]\n", " [1. 1. 1. 1.]]\n" ] } ], "source": [ "np.asarray(a)[2]=2 # np.asarray(A): converts the matrix A to an array\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `arange()`\n", "\n", "The **`arange()`** is an inbuilt numpy function that returns an ndarray object containing evenly spaced values within a defined interval. For instance, you want to create values from 1 to 10; you can use **`arange()`** function.\n", "\n", "**Syntax:**\n", "```python\n", "numpy.arange(start, stop,step) \n", "```\n", "* **`start`**: Start of interval\n", "* **`stop`**: End of interval\n", "* **`step`**: Spacing between values. Default step is 1" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:02.826823Z", "start_time": "2021-06-17T07:32:02.806317Z" }, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example 1:\n", "\n", "import numpy as np\n", "np.arange(1, 11)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to change the step, you can add a third number in the parenthesis. It will change the step." ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:11.760749Z", "start_time": "2021-06-17T07:32:11.746103Z" } }, "outputs": [ { "data": { "text/plain": [ "array([ 1, 5, 9, 13])" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example 2:\n", "\n", "import numpy as np\n", "np.arange(1, 14, 4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reshape Data\n", "\n", "In some occasions, you need to reshape the data from wide to long. You can use the reshape function for this. \n", "\n", "**Syntax:** \n", "```python\n", "numpy.reshape(a, newShape, order='C')\n", "```\n", "* **`a: Array`** that you want to reshape\n", "* **`newShape`**: The new desires shape\n", "* **`order`**: Default is **`C`** which is an essential row style." ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:15.822693Z", "start_time": "2021-06-17T07:32:15.799259Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [4 5 6]]\n" ] }, { "data": { "text/plain": [ "array([[1, 2],\n", " [3, 4],\n", " [5, 6]])" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "\n", "e = np.array([(1,2,3), (4,5,6)])\n", "print(e)\n", "e.reshape(3,2)" ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:16.773847Z", "start_time": "2021-06-17T07:32:16.751390Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3 4]\n", " [5 6 7 8]]\n" ] }, { "ename": "ValueError", "evalue": "cannot reshape array of size 8 into shape (2,3)", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mbefore\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mafter\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mbefore\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mreshape\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mafter\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mValueError\u001b[0m: cannot reshape array of size 8 into shape (2,3)" ] } ], "source": [ "before = np.array([[1,2,3,4],[5,6,7,8]])\n", "print(before)\n", "\n", "after = before.reshape((2,3))\n", "print(after)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Flatten Data\n", "\n", "When you deal with some neural network like convnet, you need to flatten the array. You can use **`flatten()`**.\n", "\n", "**Syntax:** \n", "```python\n", "numpy.flatten(order='C')\n", "```\n", "* **`a: Array`** that you want to reshape\n", "* **`newShape`**: The new desires shape\n", "* **`order`**: Default is **`C`** which is an essential row style." ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:22.298658Z", "start_time": "2021-06-17T07:32:22.285965Z" } }, "outputs": [ { "data": { "text/plain": [ "array([1, 2, 3, 4, 5, 6])" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e.flatten()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What is hstack?\n", "\n", "With hstack you can appened data horizontally. This is a very convinient function in Numpy. Lets study it with an example:" ] }, { "cell_type": "code", "execution_count": 79, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:24.994899Z", "start_time": "2021-06-17T07:32:24.981234Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Horizontal Append: [1 2 3 4 5 6]\n" ] } ], "source": [ "## Horitzontal Stack\n", "\n", "import numpy as np\n", "f = np.array([1,2,3])\n", "g = np.array([4,5,6])\n", "\n", "print('Horizontal Append:', np.hstack((f, g)))" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:30.062690Z", "start_time": "2021-06-17T07:32:30.049018Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[1., 1., 1., 1., 0., 0.],\n", " [1., 1., 1., 1., 0., 0.]])" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Horizontal stack\n", "\n", "h1 = np.ones((2,4))\n", "h2 = np.zeros((2,2))\n", "\n", "np.hstack((h1,h2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What is vstack?\n", "\n", "With vstack you can appened data vertically. Lets study it with an example:" ] }, { "cell_type": "code", "execution_count": 81, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:35.287211Z", "start_time": "2021-06-17T07:32:35.270614Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vertical Append: [[1 2 3]\n", " [4 5 6]]\n" ] } ], "source": [ "## Vertical Stack\n", "\n", "import numpy as np\n", "f = np.array([1,2,3])\n", "g = np.array([4,5,6])\n", "\n", "print('Vertical Append:', np.vstack((f, g)))" ] }, { "cell_type": "code", "execution_count": 82, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:36.316494Z", "start_time": "2021-06-17T07:32:36.302824Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[1, 2, 3, 4],\n", " [5, 6, 7, 8],\n", " [1, 2, 3, 4],\n", " [5, 6, 7, 8]])" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Vertically stacking vectors\n", "\n", "v1 = np.array([1,2,3,4])\n", "v2 = np.array([5,6,7,8])\n", "\n", "np.vstack([v1,v2,v1,v2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Generate Random Numbers\n", "\n", "To generate random numbers for Gaussian distribution use:\n", "\n", "**Syntax:**\n", "```python\n", "numpy.random.normal(loc, scale, size)\n", "```\n", "* **`loc`**: the mean. The center of distribution\n", "* **`scale`**: standard deviation.\n", "* **`size`**: number of returns" ] }, { "cell_type": "code", "execution_count": 83, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:39.497594Z", "start_time": "2021-06-17T07:32:39.486855Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5.72953035 5.8753296 4.09489662 5.67868944 5.04104088 3.95532062\n", " 5.41815566 4.89365465 5.25280107 4.94067196]\n" ] } ], "source": [ "## Generate random nmber from normal distribution\n", "\n", "normal_array = np.random.normal(5, 0.5, 10)\n", "print(normal_array)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Linspace\n", "\n", "Linspace gives evenly spaced samples.\n", "\n", "**Syntax:**\n", "```python\n", "numpy.linspace(start, stop, num, endpoint)\n", "```\n", "* **`start`**: Start of sequence\n", "* **`stop`**: End of sequence\n", "* **`num`**: Number of samples to generate. Default is 50\n", "* **`endpoint`**: If **`True`** (default), stop is the last value. If **`False`**, stop value is not included." ] }, { "cell_type": "code", "execution_count": 84, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:42.408677Z", "start_time": "2021-06-17T07:32:42.374505Z" } }, "outputs": [ { "data": { "text/plain": [ "array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778,\n", " 3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example: For instance, it can be used to create 10 values from 1 to 5 evenly spaced.\n", "\n", "import numpy as np\n", "np.linspace(1.0, 5.0, num=10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you do not want to include the last digit in the interval, you can set endpoint to **`False`**" ] }, { "cell_type": "code", "execution_count": 85, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:45.041447Z", "start_time": "2021-06-17T07:32:45.023872Z" } }, "outputs": [ { "data": { "text/plain": [ "array([1. , 1.8, 2.6, 3.4, 4.2])" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.linspace(1.0, 5.0, num=5, endpoint=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### LogSpace\n", "\n", "LogSpace returns even spaced numbers on a log scale. Logspace has the same parameters as **`np.linspace`**.\n", "\n", "**Syntax:**\n", "```python\n", "numpy.logspace(start, stop, num, endpoint)\n", "```\n", "* **`start`**: Start of sequence\n", "* **`stop`**: End of sequence\n", "* **`num`**: Number of samples to generate. Default is 50\n", "* **`endpoint`**: If **`True`** (default), stop is the last value. If **`False`**, stop value is not included." ] }, { "cell_type": "code", "execution_count": 86, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:48.769415Z", "start_time": "2021-06-17T07:32:48.749888Z" } }, "outputs": [ { "data": { "text/plain": [ "array([ 1000. , 2154.43469003, 4641.58883361, 10000. ])" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example:\n", "\n", "np.logspace(3.0, 4.0, num=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finaly, if you want to check the memory size of an element in an array, you can use **`.itemsize`**" ] }, { "cell_type": "code", "execution_count": 87, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:32:50.702001Z", "start_time": "2021-06-17T07:32:50.686382Z" } }, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = np.array([1,2,3], dtype=np.complex128)\n", "x.itemsize" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Miscellaneous" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load Data from File\n", "\n", "you can download the \"data.txt\" from **[here](https://github.com/milaan9/09_Python_NumPy_Module/blob/main/data.txt)**" ] }, { "cell_type": "code", "execution_count": 88, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:00.020702Z", "start_time": "2021-06-17T07:32:59.975781Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n", " [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n", " [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n" ] } ], "source": [ "filedata = np.genfromtxt('data.txt', delimiter=',')\n", "filedata = filedata.astype('int32') # you can also change type to 'int64'\n", "print(filedata)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Boolean Masking and Advanced Indexing" ] }, { "cell_type": "code", "execution_count": 89, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:02.250154Z", "start_time": "2021-06-17T07:33:02.239415Z" } }, "outputs": [ { "data": { "text/plain": [ "array([[False, False, False, False, True, True, False, False, False,\n", " False, False, False, False, False, False, False, False, False],\n", " [False, False, False, False, True, True, False, True, False,\n", " False, False, False, False, False, False, False, False, False],\n", " [False, False, False, False, True, False, False, False, True,\n", " False, False, False, False, False, False, False, True, True]])" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "filedata >50" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:05.290631Z", "start_time": "2021-06-17T07:33:05.271104Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n", " [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n", " [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n" ] }, { "data": { "text/plain": [ "array([196, 75, 766, 75, 55, 999, 78, 76, 88])" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(filedata)\n", "filedata[filedata >50] # '[]' will display the value of data point from the dataset" ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:06.227141Z", "start_time": "2021-06-17T07:33:06.215427Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n", " [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n", " [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n" ] }, { "data": { "text/plain": [ "array([False, False, False, False, True, True, False, True, True,\n", " False, False, False, False, False, False, False, True, True])" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(filedata)\n", "np.any(filedata > 50, axis = 0) # axis=0 refers to columns and axis=1 refers to rows in this dataset" ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:07.134352Z", "start_time": "2021-06-17T07:33:07.119708Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n", " [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n", " [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n" ] }, { "data": { "text/plain": [ "array([False, False, False, False, True, False, False, False, False,\n", " False, False, False, False, False, False, False, False, False])" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(filedata)\n", "np.all(filedata > 50, axis = 0) # '.all' refers to all the data points in row/column (based on axis=0 or axis=1)." ] }, { "cell_type": "code", "execution_count": 93, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:09.143108Z", "start_time": "2021-06-17T07:33:09.110886Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n", " [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n", " [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n" ] }, { "data": { "text/plain": [ "array([[False, False, False, False, False, True, False, False, False,\n", " False, False, False, False, False, False, False, False, False],\n", " [False, False, False, False, False, True, False, True, False,\n", " False, False, False, False, False, False, False, False, False],\n", " [False, False, False, False, False, False, False, False, True,\n", " False, False, False, False, False, False, False, True, True]])" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(filedata)\n", "(((filedata > 50) & (filedata < 100)))" ] }, { "cell_type": "code", "execution_count": 94, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:09.890166Z", "start_time": "2021-06-17T07:33:09.868686Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n", " [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n", " [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n" ] }, { "data": { "text/plain": [ "array([[ True, True, True, True, True, False, True, True, True,\n", " True, True, True, True, True, True, True, True, True],\n", " [ True, True, True, True, True, False, True, False, True,\n", " True, True, True, True, True, True, True, True, True],\n", " [ True, True, True, True, True, True, True, True, False,\n", " True, True, True, True, True, True, True, False, False]])" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(filedata)\n", "(~((filedata > 50) & (filedata < 100))) # '~' means not" ] }, { "cell_type": "code", "execution_count": 95, "metadata": { "ExecuteTime": { "end_time": "2021-06-17T07:33:12.978007Z", "start_time": "2021-06-17T07:33:12.960436Z" } }, "outputs": [ { "data": { "text/plain": [ "array([2, 3, 9])" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### You can index with a list in NumPy\n", "a = np.array([1,2,3,4,5,6,7,8,9])\n", "a [[1,2,8]] #indexes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numpy Documentation\n", "\n", "This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the **[numpy reference](https://numpy.org/doc/stable/reference/)** to find out much more about numpy." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "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.8.8" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }