{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "id": "ynE9R19cPIMT" }, "outputs": [], "source": [ "# The first step of using numpy is to tell python to import it\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": { "id": "V7NoTi0kTGVz" }, "source": [ "### 2.1 NumPy Arrays" ] }, { "cell_type": "markdown", "metadata": { "id": "cYsQgeSWalcG" }, "source": [ "**NumPy Array**\n", "* An array is a data structure that stores values of same data type.\n", "* While python lists can contain values corresponding to different data types, arrays in python can only contain values corresponding to the same data type. \n", "* However python lists fail to deliver the performance required while computing large sets of numerical data. To address this issue we use NumPy arrays.\n", "* We can create NumPy arrays by converting a list to an array.\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "-iMbhbKUS01I" }, "outputs": [], "source": [ "# defining a list of different car companies or string elements\n", "arr_str = ['Mercedes', 'BMW', 'Audi', 'Ferrari', 'Tesla']\n", "\n", "# defining a list of number of cylinders in car or numerical elements\n", "arr_num = [5, 4, 6, 7, 3]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "z8kfV796S0xz", "outputId": "50939065-2bd9-4a17-b964-5eeaa316692e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Numpy Array (arr_str): ['Mercedes' 'BMW' 'Audi' 'Ferrari' 'Tesla']\n", "Numpy Array (arr_num): [5 4 6 7 3]\n" ] } ], "source": [ "# connverting the list arr_str to a NumPy array\n", "np_arr_str = np.array(arr_str)\n", "\n", "\n", "# connverting the list arr_num to a NumPy array\n", "np_arr_num = np.array(arr_num)\n", "\n", "# checking the output\n", "print('Numpy Array (arr_str): ',np_arr_str)\n", "print('Numpy Array (arr_num): ',np_arr_num)" ] }, { "cell_type": "markdown", "metadata": { "id": "fNUnCIRbS0vz" }, "source": [ "The resuts look similar to a list but arr_str and arr_num have been converted to NumPy arrays. Let's check the data type to confirm this." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Cc_-eibuS0sr", "outputId": "ebc63d17-983d-477e-910c-ee2ae37874d5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data type of arr_str: \n", "Data type of arr_num: \n", "Data type of np_arr_str: \n", "Data type of np_arr_num: \n" ] } ], "source": [ "# printing the data type of lists\n", "print('Data type of arr_str: ',type(arr_str))\n", "print('Data type of arr_num: ',type(arr_num))\n", "\n", "# printing the data type after conversion of lists to array\n", "print('Data type of np_arr_str: ',type(np_arr_str))\n", "print('Data type of np_arr_num: ',type(np_arr_num))" ] }, { "cell_type": "markdown", "metadata": { "id": "D5MBk_c0gorg" }, "source": [ "* The above output confirms that both the lists were successfully converted to arrays" ] }, { "cell_type": "markdown", "metadata": { "id": "vO-p9figS0qt" }, "source": [ "**NumPy Matrix**" ] }, { "cell_type": "markdown", "metadata": { "id": "63nVxGI-dEFn" }, "source": [ "* A matrix is a two-dimensional data structure where elements are arranged into rows and columns.\n", "* A matrix can be created by using list of lists" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "eHL0aPSOS0fT", "outputId": "132702a2-23e9-4d5a-f075-5f88c45cf9e8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 1]\n", " [4 5 9]\n", " [1 8 9]]\n" ] } ], "source": [ "# let's say we have information of different number of cylinders in a car and we want to display them in a matrix format\n", "matrix = np.array([[1,2,1],[4,5,9],[1,8,9]])\n", "print(matrix)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1l5-7_3T2svj", "outputId": "4c2f6aea-50bd-472c-b25a-64474f2b4f19" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data type of matrix: \n" ] } ], "source": [ "print('Data type of matrix: ',type(matrix))" ] }, { "cell_type": "markdown", "metadata": { "id": "ic8DdniJAYi4" }, "source": [ "* We see that all the NumPy objects have data type as ndarray" ] }, { "cell_type": "markdown", "metadata": { "id": "s_QCIWxNPywk" }, "source": [ "### 2.2 NumPy Functions" ] }, { "cell_type": "markdown", "metadata": { "id": "9ByN9uM8dIp9" }, "source": [ "**There are different ways to create NumPy arrays using the functions available in NumPy library**" ] }, { "cell_type": "markdown", "metadata": { "id": "mJD-BCvcdjQY" }, "source": [ "**Using np.arange() function**\n", "* The np.arange() function returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. start is included but stop is excluded.\n", "* It has the following paramaters:\n", " * start : start of interval range. By default start = 0\n", " * stop : end of interval range\n", " * step : step size of interval. By default step size = 1" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "h6yhwhCfdhrO", "outputId": "fda5860e-df9b-4d27-993e-e4c565e1566c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 1 2 3 4 5 6 7 8 9]\n", "[0 1 2 3 4 5 6 7 8 9]\n" ] } ], "source": [ "arr2 = np.arange(start = 0, stop = 10) # 10 will be excluded from the output\n", "print(arr2)\n", "\n", "# or\n", "\n", "arr2 = np.arange(0,10) \n", "print(arr2)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EBQxWv87gij1", "outputId": "6cf9a56a-44f9-4115-fa7c-ac04a972c8ae" }, "outputs": [ { "data": { "text/plain": [ "array([ 0, 5, 10, 15])" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# adding a step size of 5 to create an array\n", "arr3 = np.arange(start = 0, stop = 20, step = 5)\n", "arr3" ] }, { "cell_type": "markdown", "metadata": { "id": "fadu1DMxge1S" }, "source": [ "**Using np.linspace() function**\n", "* The np.linspace() function returns numbers which are evenly distributed with respect to interval. Here the start and stop both are included. \n", "*It has the following parameters: \n", " * start: start of interval range. By default start = 0\n", " * stop: end of interval range\n", " * num : No. of samples to generate. By default num = 50" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "AvnueiSGdhb7", "outputId": "36fba42d-c65d-4bad-ef71-d61d63a8c1fe" }, "outputs": [ { "data": { "text/plain": [ "array([0. , 0.10204082, 0.20408163, 0.30612245, 0.40816327,\n", " 0.51020408, 0.6122449 , 0.71428571, 0.81632653, 0.91836735,\n", " 1.02040816, 1.12244898, 1.2244898 , 1.32653061, 1.42857143,\n", " 1.53061224, 1.63265306, 1.73469388, 1.83673469, 1.93877551,\n", " 2.04081633, 2.14285714, 2.24489796, 2.34693878, 2.44897959,\n", " 2.55102041, 2.65306122, 2.75510204, 2.85714286, 2.95918367,\n", " 3.06122449, 3.16326531, 3.26530612, 3.36734694, 3.46938776,\n", " 3.57142857, 3.67346939, 3.7755102 , 3.87755102, 3.97959184,\n", " 4.08163265, 4.18367347, 4.28571429, 4.3877551 , 4.48979592,\n", " 4.59183673, 4.69387755, 4.79591837, 4.89795918, 5. ])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "matrix2 = np.linspace(0,5) # by default 50 evenly spaced values will be generated between 0 and 5\n", "matrix2" ] }, { "cell_type": "markdown", "metadata": { "id": "zR_AydpiBToe" }, "source": [ "**How are these values getting generated?**\n", "\n", "The step size or the difference between each element will be decided by the following formula:\n", "\n", "**(stop - start) / (total elements - 1)**\n", "\n", "So, in this case:\n", "(5 - 0) / 49 = 0.10204082\n", "\n", "The first value will be 0.10204082, the second value will be 0.10204082 + 0.10204082, the third value will be 0.10204082 + 0.10204082 +0.10204082, and so on." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0VDGGmj2dhPp", "outputId": "cac9cc70-600a-4adf-e22e-434124aaf799" }, "outputs": [ { "data": { "text/plain": [ "array([10. , 11.11111111, 12.22222222, 13.33333333, 14.44444444,\n", " 15.55555556, 16.66666667, 17.77777778, 18.88888889, 20. ])" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# generating 10 evenly spaced values between 10 and 20\n", "matrix3 = np.linspace(10,20,10)\n", "matrix3" ] }, { "cell_type": "markdown", "metadata": { "id": "8Nxn51w2dhEE" }, "source": [ "**Similarly we can create matrices using the functions available in NumPy library**" ] }, { "cell_type": "markdown", "metadata": { "id": "x9brl-h9dg2b" }, "source": [ "**Using np.zeros()**\n", " \n", "* The np.zeros() is a function for creating a matrix and performing matrix operations in NumPy. \n", "* It returns a matrix filled with zeros of the given shape. \n", "* It has the following parameters: \n", " * shape : Number of rows and columns in the output matrix.\n", " * dtype: data type of the elements in the matrix, by default the value is set to `float`." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "zcfKm8ENjNQv", "outputId": "4a8d5249-f458-4d18-cb09-54c306d313c6" }, "outputs": [ { "data": { "text/plain": [ "array([[0., 0., 0., 0., 0.],\n", " [0., 0., 0., 0., 0.],\n", " [0., 0., 0., 0., 0.]])" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "matrix4 = np.zeros([3,5])\n", "matrix4" ] }, { "cell_type": "markdown", "metadata": { "id": "8jy4YykQjICK" }, "source": [ "**Using np.ones()**\n", "\n", "* The np.ones() is another function for creating a matrix and performing matrix operations in NumPy. \n", "* It returns a matrix of given shape and type, filled with ones.\n", "* It has the following parameters: \n", " * shape : Number of rows and columns in the output matrix.\n", " * dtype: data type of the elements in the matrix, by default the value is set to `float`." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "JJ-hv5dcjRN1", "outputId": "36153c38-6165-452a-a1ac-d38a31f07661" }, "outputs": [ { "data": { "text/plain": [ "array([[1., 1., 1., 1., 1.],\n", " [1., 1., 1., 1., 1.],\n", " [1., 1., 1., 1., 1.]])" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "matrix5 = np.ones([3,5])\n", "matrix5" ] }, { "cell_type": "markdown", "metadata": { "id": "ge-0i4W2jH4S" }, "source": [ "**Using np.eye()**\n", "* The np.eye() is a function for creating a matrix and performing matrix operations in NumPy. \n", "* It returns a matrix with ones on the diagonal and zeros elsewhere. \n", "* It has the following parameters:\n", " * n: Number of rows and columns in the output matrix \n", " * dtype: data type of the elements in the matrix, by default the value is set to `float`." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "2a0_OXeWjHou", "outputId": "9830d274-756f-4a26-aa37-5dca29341c8b" }, "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": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "matrix6 = np.eye(5)\n", "matrix6" ] }, { "cell_type": "markdown", "metadata": { "id": "DkJp6gB1dgHl" }, "source": [ "**We can also convert a one dimension array to a matrix. This can be done by using the np.reshape() function.**" ] }, { "cell_type": "markdown", "metadata": { "id": "ifxHtcyyuVsX" }, "source": [ "* The shape of an array basically tells the number of elements and dimensions of the array. Reshaping a Numpy array simply means changing the shape of the given array. \n", "* By reshaping an array we can add or remove dimensions or change number of elements in each dimension. \n", "* In order to reshape a NumPy array, we use the reshape method with the given array. \n", "* **Syntax:** array.reshape(shape) \n", " * shape: a tuple given as input, the values in tuple will be the new shape of the array." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "iYbHCKdPk5hb", "outputId": "69eb5afb-0861-4b01-e98f-4419f3939f18" }, "outputs": [ { "data": { "text/plain": [ "array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# defining an array with values 0 to 9\n", "arr4 = np.arange(0,10) \n", "arr4" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SE6wnu1MlbXv", "outputId": "6a5ed1f8-4bb9-459e-fb12-f38cd34eca1d" }, "outputs": [ { "data": { "text/plain": [ "array([[0, 1, 2, 3, 4],\n", " [5, 6, 7, 8, 9]])" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# reshaping the array arr4 to a 2 x 5 matrix\n", "arr4_reshaped = arr4.reshape((2,5))\n", "arr4_reshaped" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "KbuGcnPLFT2m", "outputId": "32b75568-94ac-423b-abf6-7476e614e7f4" }, "outputs": [ { "data": { "text/plain": [ "array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr4" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 183 }, "id": "HRqcE-TT_-dQ", "outputId": "5a1d0d35-93b0-4afd-899e-d30c7cf71074" }, "outputs": [ { "ename": "ValueError", "evalue": "ignored", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# reshaping the array arr4 to a 2 x 6 matrix\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0marr4\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreshape\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: cannot reshape array of size 10 into shape (2,6)" ] } ], "source": [ "# reshaping the array arr4 to a 2 x 6 matrix\n", "arr4.reshape((2,6))" ] }, { "cell_type": "markdown", "metadata": { "id": "7DGMoYswCocf" }, "source": [ "* This did not work because we have 10 elements which we are trying to fit in a 2 X 6 shape which will require 12 elements." ] }, { "cell_type": "markdown", "metadata": { "id": "lNd_TddVQtWI" }, "source": [ "**NumPy can also perform a large number of different mathematical operations and it provides different functions to do so.**\n", "\n", "NumPy provides:\n", "1. Trigonometric functions \n", "2. Exponents and Logarithmic functions\n", "3. Functions for arithmetic operations between arrays and matrices" ] }, { "cell_type": "markdown", "metadata": { "id": "CE9wPRdYn5IB" }, "source": [ "**Trigonometric functions**" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6iKAU71XQBXn", "outputId": "09199fcb-7f25-4042-8ce2-67d7850f40f4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sine Function: -0.7568024953079282\n", "Cosine Function: -0.6536436208636119\n", "Tan Function 1.1578212823495775\n" ] } ], "source": [ "print('Sine Function:',np.sin(4))\n", "print('Cosine Function:',np.cos(4))\n", "print('Tan Function',np.tan(4))" ] }, { "cell_type": "markdown", "metadata": { "id": "9QWy471mQEXT" }, "source": [ "**Exponents and Logarithmic functions**" ] }, { "cell_type": "markdown", "metadata": { "id": "BBKFBoABoyRx" }, "source": [ "* Exponents" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "aanbLXltoDgt", "outputId": "7ac751b7-9076-470b-eff1-80eeca56be42" }, "outputs": [ { "data": { "text/plain": [ "7.38905609893065" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.exp(2)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9VUfgN_oomI7", "outputId": "4af679a2-d011-4ad2-9f84-14a7ef086678" }, "outputs": [ { "data": { "text/plain": [ "array([ 7.3890561 , 54.59815003, 403.42879349])" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr5 = np.array([2,4,6])\n", "np.exp(arr5)" ] }, { "cell_type": "markdown", "metadata": { "id": "BgTCC-v6ouZn" }, "source": [ "* Logarithms" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7V8RWfDipHOQ", "outputId": "40468f42-1de4-4d1d-c2cf-60c491d190f0" }, "outputs": [ { "data": { "text/plain": [ "0.6931471805599453" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# by default NumPy takes the base of log as e\n", "np.log(2)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "CH5eCec2pJLo", "outputId": "ce25cb54-452f-4724-b61a-198bc2027cc2" }, "outputs": [ { "data": { "text/plain": [ "array([0.69314718, 1.38629436, 1.79175947])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.log(arr5)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bgam8aXTpOVc", "outputId": "520df4df-adcf-4365-9725-1347e7656ebc" }, "outputs": [ { "data": { "text/plain": [ "0.9030899869919435" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "## log with base 10\n", "np.log10(8) " ] }, { "cell_type": "markdown", "metadata": { "id": "jDCujvq0pWZr" }, "source": [ "**Arithmetic Operations on arrays**" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SXFDL0TeKJZT", "outputId": "88bbcc2e-4963-4607-fab6-2a5edb899e08" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5, 6]\n" ] } ], "source": [ "# arithmetic on lists\n", "\n", "l1 = [1,2,3]\n", "l2 = [4,5,6]\n", "print(l1+l2)\n", "# this does not behave as you would expect!\n" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "MHZKZFP8ppQx", "outputId": "c2aacb8a-7ae1-40f3-9c76-25f8222247c4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arr7: [1 2 3 4 5]\n", "arr8: [3 4 5 6 7]\n" ] } ], "source": [ "# we can +-*/ arrays together\n", "\n", "# defining two arrays\n", "arr7 = np.arange(1,6)\n", "print('arr7:', arr7)\n", "\n", "arr8 = np.arange(3,8)\n", "print('arr8:', arr8)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "xkMkQOL8rHOw", "outputId": "28d1dfd5-9dcc-43e3-e6ca-74af5cd26486" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Addition: [ 4 6 8 10 12]\n", "Subtraction: [2 2 2 2 2]\n", "Multiplication: [ 3 8 15 24 35]\n", "Division: [0.33333333 0.5 0.6 0.66666667 0.71428571]\n", "Inverse: [1. 0.5 0.33333333 0.25 0.2 ]\n", "Powers: [ 1 16 243 4096 78125]\n" ] } ], "source": [ "print('Addition: ',arr7+arr8)\n", "print('Subtraction: ',arr8-arr7)\n", "print('Multiplication:' , arr7*arr8)\n", "print('Division:', arr7/arr8)\n", "print('Inverse:', 1/arr7)\n", "print('Powers:', arr7**arr8) # in python, powers are achieved using **, NOT ^!!! ^ does something completely different!\n" ] }, { "cell_type": "markdown", "metadata": { "id": "SrE8fcrFtt7c" }, "source": [ "**Operations on Matrices**" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "p-lZfDhUrb2b", "outputId": "4d0618b6-0d12-4f61-cf5a-b967db9bbe4c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [4 5 6]\n", " [7 8 9]]\n", "[[1. 0. 0.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]]\n" ] } ], "source": [ "matrix7 = np.arange(1,10).reshape(3,3)\n", "print(matrix7)\n", "\n", "matrix8 = np.eye(3)\n", "print(matrix8)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "VGBAxsUUtyts", "outputId": "cd1b0dd5-1b4f-4815-8192-7ff4c22970f3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Addition: \n", " [[ 2. 2. 3.]\n", " [ 4. 6. 6.]\n", " [ 7. 8. 10.]]\n", "Subtraction: \n", " [[0. 2. 3.]\n", " [4. 4. 6.]\n", " [7. 8. 8.]]\n", "Multiplication: \n", " [[1. 0. 0.]\n", " [0. 5. 0.]\n", " [0. 0. 9.]]\n", "Division: \n", " [[ 1. inf inf]\n", " [inf 5. inf]\n", " [inf inf 9.]]\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in true_divide\n", " after removing the cwd from sys.path.\n" ] } ], "source": [ "print('Addition: \\n', matrix7+matrix8)\n", "print('Subtraction: \\n ', matrix7-matrix8)\n", "print('Multiplication: \\n', matrix7*matrix8)\n", "print('Division: \\n', matrix7/matrix8)" ] }, { "cell_type": "markdown", "metadata": { "id": "c7jHF8Od6mHH" }, "source": [ "* RuntimeWarning: Errors which occur during program execution(run-time) after successful compilation are called run-time errors. \n", "* One of the most common run-time error is division by zero also known as Division error. \n", "* Due to division by zero error, we are getting inf (infinity) values because 1/0 is not a defined operation." ] }, { "cell_type": "markdown", "metadata": { "id": "3WYcA-OxyL9Y" }, "source": [ "**Linear algebra matrix multiplication**" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "nc0PAuG3sM6A", "outputId": "114bbac2-1d8a-4c8d-fd87-d5d077b9058c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First Matrix: \n", " [[1 2 3]\n", " [4 5 6]\n", " [7 8 9]]\n", "Second Matrix: \n", " [[11 12 13]\n", " [14 15 16]\n", " [17 18 19]]\n", "\n", "Multiplication: \n", " [[ 90 96 102]\n", " [216 231 246]\n", " [342 366 390]]\n" ] } ], "source": [ "matrix9 = np.arange(1,10).reshape(3,3)\n", "print('First Matrix: \\n',matrix9)\n", "\n", "matrix10 = np.arange(11,20).reshape(3,3)\n", "print('Second Matrix: \\n',matrix10)\n", "print('')\n", "# taking linear algebra matrix multiplication (some may have heard this called the dot product)\n", "print('Multiplication: \\n', matrix9 @ matrix10)" ] }, { "cell_type": "markdown", "metadata": { "id": "LQVkMw7Iynfu" }, "source": [ "**Transpose of a matrix**" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DJp3NtsrsSM4", "outputId": "f4a31d84-dba8-4d9a-c2f1-22500d08f49a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [4 5 6]\n", " [7 8 9]]\n" ] } ], "source": [ "print(matrix9)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "MDKJgUlptKet", "outputId": "02f933fe-5d15-4d9d-cbaf-f8128df10709" }, "outputs": [ { "data": { "text/plain": [ "array([[1, 4, 7],\n", " [2, 5, 8],\n", " [3, 6, 9]])" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# taking transpose of matrix\n", "np.transpose(matrix9)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PwwpvruatMRj", "outputId": "c7e89f4b-1226-4664-c0a0-27793f54d1cc" }, "outputs": [ { "data": { "text/plain": [ "array([[1, 4, 7],\n", " [2, 5, 8],\n", " [3, 6, 9]])" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# another way of taking a transpose\n", "matrix9.T" ] }, { "cell_type": "markdown", "metadata": { "id": "YSl_vQk70bCS" }, "source": [ "**Function to find minimum and maximum values**" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "TmPZB7tu0a2c", "outputId": "d1829f3f-bcdc-4e7d-f162-7048d1bc7a8f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 2 3]\n", " [4 5 6]\n", " [7 8 9]]\n" ] } ], "source": [ "print(matrix9)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "394LL_BZ0alr", "outputId": "d941df07-08d5-41a8-e37b-deab1b4647e6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Minimum value: 1\n" ] } ], "source": [ "print('Minimum value: ',np.min(matrix9))" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "SVs2Zx0J0ac3", "outputId": "06454e1d-c4e5-4ecf-e9cf-755f93b56990" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Maximum value: 9\n" ] } ], "source": [ "print('Maximum value: ',np.max(matrix9))" ] }, { "cell_type": "markdown", "metadata": { "id": "7NNtvTmh0aRf" }, "source": [ "**Function to generate random samples**" ] }, { "cell_type": "markdown", "metadata": { "id": "XO47Cq8L3Gb3" }, "source": [ "**Using np.random.rand function**\n", "\n", "* The np.random.rand returns a random NumPy array whose element(s) are drawn randomly from the uniform distribution over [0,1). (including 0 but excluding 1). \n", "* **Syntax** - np.random.rand(d0,d1)\n", " * d0,d1 – It represents the dimension of the required array given as int, where d1 is optional. " ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Neq3fBGH4N7F", "outputId": "2f6b4a8b-dcc1-4c90-defe-1a84854ea3f9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.1849803 0.40907032 0.43320279 0.20128129 0.14866145]\n" ] } ], "source": [ "# Generating random values in an array\n", "rand_mat = np.random.rand(5)\n", "print(rand_mat)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "QQHFrAce1570", "outputId": "e03aad3b-e7be-4b72-e9b3-e578f183f6d3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0.74674765 0.39426306 0.83013246 0.59158138 0.33519229]\n", " [0.30061878 0.74846432 0.85288519 0.22903368 0.77846736]\n", " [0.03130384 0.25880234 0.28800138 0.39070634 0.74455262]\n", " [0.1001066 0.2882508 0.5651407 0.66282803 0.08676726]\n", " [0.61007231 0.95430991 0.75879184 0.29681776 0.22827461]]\n" ] } ], "source": [ "# * Generating random values in a matrix\n", "rand_mat = np.random.rand(5,5) # uniform random variable\n", "print(rand_mat)" ] }, { "cell_type": "markdown", "metadata": { "id": "VvvK-7Sh3PfD" }, "source": [ "**Using np.random.randn function**\n", "\n", "* The np.random.randn returns a random numpy array whose sample(s) are drawn randomly from the standard normal distribution (Mean as 0 and standard deviation as 1)\n", "\n", "* **Syntax** - np.random.randn(d0,d1)\n", " * d0,d1 – It represents the dimension of the output, where d1 is optional." ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ll_boKdQ4Y-b", "outputId": "d0c6a31c-b66a-47e8-ab1a-af3b829066ae" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.66222394 2.44126474 0.41205704 0.04786961 1.04811775]\n" ] } ], "source": [ "# Generating random values in an array\n", "rand_mat2 = np.random.randn(5) \n", "print(rand_mat2)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1jaiT-oZ2CyD", "outputId": "ead08d0e-f194-4631-aeaa-e90dcc245c8e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0.2820466 0.31424354 -0.51386568 -0.45097053 -1.12771526]\n", " [ 0.05229145 -2.12906168 0.78210721 0.74668925 -0.73695471]\n", " [ 0.70736688 0.41313492 -0.84423005 -0.11143511 1.8729083 ]\n", " [ 0.5017195 0.71736157 1.49309021 0.45919776 -0.13238773]\n", " [ 1.10234237 -0.20650805 -0.91874445 1.11226684 -0.45414538]]\n" ] } ], "source": [ "# Generating random values in a matrix\n", "rand_mat2 = np.random.randn(5,5) \n", "print(rand_mat2)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "TldcCrOS5ulV", "outputId": "754c72ad-7f9b-459d-9640-72eba1e5a46f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mean: 0.11722991137038243\n", "Standard Deviation: 0.883066783507808\n" ] } ], "source": [ "# Let's check the mean and standard deviation of rand_mat2\n", "print('Mean:',np.mean(rand_mat2))\n", "print('Standard Deviation:',np.std(rand_mat2))" ] }, { "cell_type": "markdown", "metadata": { "id": "66BnHAPW6Ere" }, "source": [ "* We observe that the mean is very close to 0 and standard deviation is very close to 1." ] }, { "cell_type": "markdown", "metadata": { "id": "T_0yFxGh3U2D" }, "source": [ "**Using np.random.randint function**\n", "\n", "* The np.random.randint returns a random numpy array whose element(s) are drawn randomly from low (inclusive) to the high (exclusive) range. \n", "\n", "* **Syntax** - np.random.randint(low, high, size) \n", "\n", " * low – It represents the lowest inclusive bound of the distribution from where the sample can be drawn.\n", " * high – It represents the upper exclusive bound of the distribution from where the sample can be drawn. \n", " * size – It represents the shape of the output. " ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "vLPM7a0N2EHA", "outputId": "212b2ad7-46cb-4e30-f1cd-4d559db99fcb" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 2 3 1 2 4 3 3 4 4]\n" ] } ], "source": [ "# Generating random values in an array\n", "rand_mat3 = np.random.randint(1,5,10)\n", "print(rand_mat3)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "u9YqKltk486n", "outputId": "772fdcf1-1dcb-4fd7-f738-3324285b6ff3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 5 2 1 2]\n", " [6 1 7 1 8]\n", " [6 6 5 2 5]\n", " [4 3 7 3 1]\n", " [2 6 1 1 5]]\n" ] } ], "source": [ "# Generating random values in a matrix\n", "rand_mat3 = np.random.randint(1,10,[5,5])\n", "print(rand_mat3)" ] }, { "cell_type": "markdown", "metadata": { "id": "J-K_ecWJ6M6n" }, "source": [ "### 2.3 Accessing the entries of a Numpy Array" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4Tiy6KJw3a5A", "outputId": "40debad6-e1cc-4c14-dce4-c69453246dea" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.61610084 0.256255 -1.02474372 1.69663775 0.14830608 0.0587465\n", " -0.58451129 0.09827507 1.38926594 0.52114238]\n" ] } ], "source": [ "# let's generate an array with 10 random values\n", "rand_arr = np.random.randn(10)\n", "print(rand_arr)" ] }, { "cell_type": "markdown", "metadata": { "id": "gJlNtFKwaZUv" }, "source": [ "* Accessing one element from an array" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PtSqbI-Y3awc", "outputId": "af3f7205-de8c-49b9-b3dd-a976a5ef4e4c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-0.5845112936165019\n" ] } ], "source": [ "# accessing the 6 th entry of rand_arr\n", "print(rand_arr[6])" ] }, { "cell_type": "markdown", "metadata": { "id": "Ywt2eQx-aZUv" }, "source": [ "* Accessing multiple elements from an array" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "HZ8Yb_3h3amG", "outputId": "750954eb-c35c-45ab-8d97-758702a865e6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0.14830608 0.0587465 -0.58451129 0.09827507 1.38926594]\n" ] } ], "source": [ "# we can access multiple entries at once using\n", "print(rand_arr[4:9])" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "pNcRsFbK3aZP", "outputId": "c253f8c1-bba7-40cc-d54c-86863c6e8798" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index of values to access: [3 6 9]\n", "[ 1.69663775 -0.58451129 0.52114238]\n" ] } ], "source": [ "# we can also access multiple non-consecutive entries using np.arange\n", "print('Index of values to access: ',np.arange(3,10,3))\n", "print(rand_arr[np.arange(3,10,3)])" ] }, { "cell_type": "markdown", "metadata": { "id": "m0_dOkPKc7bL" }, "source": [ "**Accessing arrays using logical operations**" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "_8v77EwOcwPM", "outputId": "c89f7bdb-ccd0-4a69-d914-2c754c93c6ec" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.61610084 0.256255 -1.02474372 1.69663775 0.14830608 0.0587465\n", " -0.58451129 0.09827507 1.38926594 0.52114238]\n" ] } ], "source": [ "print(rand_arr)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "u7QvbkGfc_Mf", "outputId": "e8d20b7e-19a9-4128-982c-787e19412c1a" }, "outputs": [ { "data": { "text/plain": [ "array([False, True, False, True, True, True, False, True, True,\n", " True])" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rand_arr>0" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PwjFRjDiczAS", "outputId": "a41c1aa0-7fef-4053-f243-7b8df7eed3d1" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Values greater than 0: [0.256255 1.69663775 0.14830608 0.0587465 0.09827507 1.38926594\n", " 0.52114238]\n", "Values less than 0: [-0.61610084 -1.02474372 -0.58451129]\n" ] } ], "source": [ "# accessing all the values of rand_arr which are greater than 0\n", "print('Values greater than 0: ',rand_arr[rand_arr>0])\n", "\n", "# accessing all the values of rand_arr which are less than 0\n", "print('Values less than 0: ',rand_arr[rand_arr<0])" ] }, { "cell_type": "markdown", "metadata": { "id": "9j2nb_lX3aKJ" }, "source": [ "**Accessing the entries of a Matrix**" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "rUT3MtuX3Z-o", "outputId": "2d5844c9-f29e-487d-f599-510db9ccce66" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0.66008467 -0.91860835 -0.91768744 -0.56565779 -0.19013084]\n", " [ 0.68692112 1.20042327 -0.55648032 0.51675983 -1.13325252]\n", " [ 1.76883638 -0.85498119 1.89998922 -1.0658905 1.50531893]\n", " [ 0.77388464 -1.24206763 0.75631041 1.01940576 0.89747448]\n", " [ 0.37852758 -1.36846366 -0.91566544 -0.47943544 -0.20226054]]\n" ] } ], "source": [ "# let's generate an array with 10 random values\n", "rand_mat = np.random.randn(5,5)\n", "print(rand_mat)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "aH5KNWYJ8AAi", "outputId": "95dddd73-7b44-441f-f1ca-9ef4bdbe517f" }, "outputs": [ { "data": { "text/plain": [ "array([ 0.68692112, 1.20042327, -0.55648032, 0.51675983, -1.13325252])" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# acessing the second row of the rand_mat\n", "rand_mat[1]" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "cKPauEeS3Zya", "outputId": "87ba94bb-f7ea-41f9-ee96-94bb03582dbd" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-0.5564803167132045\n", "-0.5564803167132045\n" ] } ], "source": [ "# acessing third element of the second row\n", "print(rand_mat[1][2])\n", "\n", "#or \n", "\n", "print(rand_mat[1,2])" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "md90xMiX3ZhX", "outputId": "d9b022f4-9775-4033-ce20-de29677fffc1" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-0.91860835 -0.91768744]\n", " [ 1.20042327 -0.55648032]]\n" ] } ], "source": [ "# accessing first two rows with second and third column \n", "print(rand_mat[0:2,1:3])" ] }, { "cell_type": "markdown", "metadata": { "id": "ZQIPaCTxdTkx" }, "source": [ "**Accessing matrices using logical operations**" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "FPWAgqcMdTkx", "outputId": "22130ab2-c84a-48b3-dd19-2ce235cb1bb8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0.66008467 -0.91860835 -0.91768744 -0.56565779 -0.19013084]\n", " [ 0.68692112 1.20042327 -0.55648032 0.51675983 -1.13325252]\n", " [ 1.76883638 -0.85498119 1.89998922 -1.0658905 1.50531893]\n", " [ 0.77388464 -1.24206763 0.75631041 1.01940576 0.89747448]\n", " [ 0.37852758 -1.36846366 -0.91566544 -0.47943544 -0.20226054]]\n" ] } ], "source": [ "print(rand_mat)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5pBwxeo_dTky", "outputId": "ba0e5fe5-db2b-4f98-d6b6-125f8516c493" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Values greater than 0: \n", " [0.66008467 0.68692112 1.20042327 0.51675983 1.76883638 1.89998922\n", " 1.50531893 0.77388464 0.75631041 1.01940576 0.89747448 0.37852758]\n", "Values less than 0: \n", " [-0.91860835 -0.91768744 -0.56565779 -0.19013084 -0.55648032 -1.13325252\n", " -0.85498119 -1.0658905 -1.24206763 -1.36846366 -0.91566544 -0.47943544\n", " -0.20226054]\n" ] } ], "source": [ "# accessing all the values of rand_mat which are greater than 0\n", "print('Values greater than 0: \\n ',rand_mat[rand_mat>0])\n", "\n", "# accessing all the values of rand_mat which are less than 0\n", "print('Values less than 0: \\n',rand_mat[rand_mat<0])" ] }, { "cell_type": "markdown", "metadata": { "id": "Rbc_yo5T8mmS" }, "source": [ "**Modifying the entries of an Array**" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "2P57NUFJ8mMA", "outputId": "4c6f5d19-95d7-4ccc-ff28-fe76e18228d7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.61610084 0.256255 -1.02474372 1.69663775 0.14830608 0.0587465\n", " -0.58451129 0.09827507 1.38926594 0.52114238]\n" ] } ], "source": [ "print(rand_arr)\n" ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5dTfDf2d-DF7", "outputId": "c9f149ef-4463-401e-cb3d-fd6df3f1c404" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.61610084 0.256255 -1.02474372 5. 5. 0.0587465\n", " -0.58451129 0.09827507 1.38926594 0.52114238]\n" ] } ], "source": [ "# let's change some values in an array!\n", "# changing the values of index value 3 and index value 4 to 5\n", "rand_arr[3:5] = 5\n", "print(rand_arr)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "dC1yVJLT-H9H", "outputId": "cac466b1-e851-46d3-d939-e8071ad058e7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 2. 3. -1.02474372 5. 5. 0.0587465\n", " -0.58451129 0.09827507 1.38926594 0.52114238]\n" ] } ], "source": [ "# changing the values of index value 0 and index value 1 to 2 and 3 respectively\n", "rand_arr[0:2] = [2,3]\n", "print(rand_arr)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "wT3ishttMugE", "outputId": "0201c43a-03b1-489b-ff70-dae97a8c0557" }, "outputs": [ { "data": { "text/plain": [ "array([65. , 65. , -1.02474372, 65. , 65. ,\n", " 65. , -0.58451129, 65. , 65. , 65. ])" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# modify entries using logical references\n", "rand_arr[rand_arr>0] = 65\n", "rand_arr" ] }, { "cell_type": "markdown", "metadata": { "id": "lhoMit_Da8F4" }, "source": [ "**Modifying the entries of a Matrix**" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "fJ02uz8obsqC", "outputId": "235baae0-f38e-4a43-9f8e-5e422b8973b7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1 5 2 1 2]\n", " [6 1 7 1 8]\n", " [6 6 5 2 5]\n", " [4 3 7 3 1]\n", " [2 6 1 1 5]]\n" ] } ], "source": [ "print(rand_mat3)" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "dVNbm4oKNtkr", "outputId": "40ac65ce-41bd-4bc3-bc61-0ce7abad83c1" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix before modification: \n", " [[1 5 2 1 2]\n", " [6 1 7 1 8]\n", " [6 6 5 2 5]\n", " [4 3 7 3 1]\n", " [2 6 1 1 5]]\n", "Matrix after modification: \n", " [[1 5 2 1 2]\n", " [6 1 7 0 0]\n", " [6 6 5 0 0]\n", " [4 3 7 3 1]\n", " [2 6 1 1 5]]\n" ] } ], "source": [ "# changing the values of the 4th and 5th element of the second and third rows of the matrix to 0\n", "print('Matrix before modification: \\n',rand_mat3)\n", "rand_mat3[1:3,3:5] = 0\n", "print('Matrix after modification: \\n',rand_mat3)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uP3butowNtvp", "outputId": "3d35ab10-b02c-4d68-b62d-5cb6f870fc6a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0.66008467 -0.91860835 -0.91768744]\n", " [ 0.68692112 1.20042327 -0.55648032]]\n" ] } ], "source": [ "# extracting the first 2 rows and first 3 columns from the matrix\n", "sub_mat = rand_mat[0:2,0:3]\n", "print(sub_mat)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "3DgctOvENt14", "outputId": "a467bb0d-8290-4f93-d50c-3a23c634d70c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[3. 3. 3.]\n", " [3. 3. 3.]]\n" ] } ], "source": [ "# changing all the values of the extracted matrix to 3\n", "sub_mat[:] = 3\n", "print(sub_mat)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "hskgV9vG9lxx", "outputId": "ec90a56c-2f27-485e-e7b4-ef3a82b942a2" }, "outputs": [ { "data": { "text/plain": [ "array([[ 3. , 3. , 3. , -0.56565779, -0.19013084],\n", " [ 3. , 3. , 3. , 0.51675983, -1.13325252],\n", " [ 1.76883638, -0.85498119, 1.89998922, -1.0658905 , 1.50531893],\n", " [ 0.77388464, -1.24206763, 0.75631041, 1.01940576, 0.89747448],\n", " [ 0.37852758, -1.36846366, -0.91566544, -0.47943544, -0.20226054]])" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# what happened to rand_mat when we change sub_mat?\n", "rand_mat" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PryCb2h29sHx", "outputId": "e1fdf33d-7740-4cf8-e99b-9d985643ef81" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 2.0112384 0.49785818 -1.25183808 1.68261636 0.51405209]\n", " [ 0.19861572 -1.02405923 1.47588997 0.9095827 1.44913937]\n", " [ 1.17797906 2.2230628 1.0897073 -0.61658736 1.30247375]\n", " [-0.72899737 0.35296055 -1.28267073 -0.12390565 0.74816716]\n", " [ 1.54172729 0.23114564 -0.06203034 -0.00718632 -0.32182532]]\n", "[[3. 3. 3.]\n", " [3. 3. 3.]]\n", "[[ 2.0112384 0.49785818 -1.25183808 1.68261636 0.51405209]\n", " [ 0.19861572 -1.02405923 1.47588997 0.9095827 1.44913937]\n", " [ 1.17797906 2.2230628 1.0897073 -0.61658736 1.30247375]\n", " [-0.72899737 0.35296055 -1.28267073 -0.12390565 0.74816716]\n", " [ 1.54172729 0.23114564 -0.06203034 -0.00718632 -0.32182532]]\n" ] } ], "source": [ "# to prevent this behavior we need to use the .copy() method when we assign sub_mat\n", "# this behavior is the source of MANY errors for early python users!!!\n", "\n", "rand_mat = np.random.randn(5,5)\n", "print(rand_mat)\n", "sub_mat = rand_mat[0:2,0:3].copy()\n", "sub_mat[:] = 3\n", "print(sub_mat)\n", "print(rand_mat)" ] }, { "cell_type": "markdown", "metadata": { "id": "Uhy7xJlW0aDT" }, "source": [ "### 2.4 Saving and Loading a NumPy array" ] }, { "cell_type": "markdown", "metadata": { "id": "qlyONcw5FeSh" }, "source": [ "**Let's save some NumPy objects on the disk for use later!**" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "gikqL10PzrC1", "outputId": "a57bedae-1916-4471-9654-ddc1561896d9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mounted at /content/drive\n" ] } ], "source": [ "from google.colab import drive\n", "drive.mount('/content/drive')" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "G_w4dYUtFzZO", "outputId": "b964d947-2c52-4ea4-9926-c3aea1d4d050" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[7 2 9 7 2]\n", " [6 6 5 7 2]]\n", "\n", "[[10 16 12 17 18]\n", " [19 12 11 13 17]]\n" ] } ], "source": [ "# creating a random matrices\n", "randint_matrix1 = np.random.randint(1,10,10).reshape(2,5)\n", "print(randint_matrix1)\n", "print('')\n", "randint_matrix2 = np.random.randint(10,20,10).reshape(2,5)\n", "print(randint_matrix2)" ] }, { "cell_type": "markdown", "metadata": { "id": "rysUk_pSFU1O" }, "source": [ "**Using np.save() function**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "k9TyLFJ-tkU2" }, "outputs": [], "source": [ "np.save('/content/drive/MyDrive/Python Course/saved_file_name',randint_matrix1)" ] }, { "cell_type": "markdown", "metadata": { "id": "VMfbQlc2FYNl" }, "source": [ "**Using np.savez() function**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "dhtVPefIRfGP" }, "outputs": [], "source": [ "np.savez('/content/drive/MyDrive/Python Course/multiple_files',randint_matrix1=randint_matrix1,randint_matrix2=randint_matrix2)" ] }, { "cell_type": "markdown", "metadata": { "id": "hDbZNqdLDj35" }, "source": [ "* The files will be saved in the directory where the Jupyter Notebook is located.\n", "* With np.save() function, we can save an array/matrix to a NumPy .npy format.\n", "* np.savez() function has an advantage over np.save() function because with np.savez(), we can store several arrays/matrices into a single file in uncompressed .npz format." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "h7mYd86cZeTq" }, "outputs": [], "source": [ "# now let's load it\n", "loaded_arr = np.load('/content/drive/MyDrive/Python Course/saved_file_name.npy')\n", "loaded_multi = np.load('/content/drive/MyDrive/Python Course/multiple_files.npz')\n", "\n", "print(loaded_arr)\n", "print('')\n", "print(loaded_multi)" ] }, { "cell_type": "markdown", "metadata": { "id": "21XxghDDG69T" }, "source": [ "* We see that .npy file has been loaded but the .npz file is returning a memory location.\n", "* Let's see how to load the values stored in .npz file." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "VezEM4uPZeZk" }, "outputs": [], "source": [ "print('1st Matrix: \\n',loaded_multi['randint_matrix1'])\n", "print('2nd Matrix: \\n',loaded_multi['randint_matrix2'])\n", "\n", "new_matrix = loaded_multi['randint_matrix1']\n", "print('New Matrix: \\n',new_matrix)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "AyyZjATxZefd" }, "outputs": [], "source": [ "# we can also save/load text files...but only single variables\n", "np.savetxt('/content/drive/MyDrive/Python Course/text_file_name.txt',randint_matrix1,delimiter=',')\n", "rand_mat_txt = np.loadtxt('/content/drive/MyDrive/Python Course/text_file_name.txt',delimiter=',')\n", "print(randint_matrix1)\n", "print('')\n", "print(rand_mat_txt)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "WiTOg-jNzE82" }, "outputs": [], "source": [] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "Hands-on Notebook-NumPy.ipynb", "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.7" } }, "nbformat": 4, "nbformat_minor": 1 }