diff --git a/book/_toc.yml b/book/_toc.yml index d7d5ba6..f7f00c1 100644 --- a/book/_toc.yml +++ b/book/_toc.yml @@ -12,11 +12,11 @@ parts: - file: python.md title: Programming and Python - file: toolbox.md - - caption: Course Contents + - caption: "Part 1: Python Standard Library " numbered: true chapters: - file: basics.md - title: Beyond the Basics + title: Basics sections: - file: basics/hello.ipynb title: Your First Script @@ -55,10 +55,28 @@ parts: - file: modules/modules.ipynb title: Modules - file: modules/Exercises/01.ipynb - - file: 05/Theory/01.ipynb + - file: errors/intro.md + title: Errors + sections: + - file: errors/error_types.ipynb + - file: errors/traceback.ipynb + - file: errors/raise_errors.ipynb + - file: errors/handling_errors.ipynb + - file: errors/asserts.ipynb + - caption: "Part 2: Other Libraries" + numbered: true + chapters: + - file: numpy.md + title: Numpy sections: - - file: 05/Exercises/01.ipynb - - file: 05/Exercises/02.ipynb + - file: numpy/introduction.ipynb + - file: numpy/1d.ipynb + - file: numpy/2d.ipynb + title: "Two-Dimensional arrays and matrices" + - file: numpy/Exercises/01.ipynb + title: "Exercise 1: Airplane velocity" + - file: numpy/Exercises/02.ipynb + title: "Exercise 2: Bending Moment on Bridge" - file: 06/Theory/01.ipynb sections: - file: 06/Exercises/01.ipynb @@ -67,14 +85,6 @@ parts: - file: 07/Exercises/01.ipynb - file: 08/sympy title: 8. SymPy - - file: 09/intro.md - title: 9. Errors - sections: - - file: 09/error_types.ipynb - - file: 09/traceback.ipynb - - file: 09/raise_errors.ipynb - - file: 09/handling_errors.ipynb - - file: 09/asserts.ipynb - caption: End of course survey numbered: false chapters: @@ -113,7 +123,12 @@ parts: sections: - file: modules/nutshell/modules.ipynb title: Modules - - file: 04/In_a_Nutshell/01.ipynb + - file: numpy/nutshell.md + title: Numpy + sections: + - file: numpy/nutshell/numpy.ipynb + title: Numpy + - file: numpy/In_a_Nutshell/01.ipynb - file: 05/In_a_Nutshell/01.ipynb - file: 06/In_a_Nutshell/01.ipynb - file: 07/In_a_Nutshell/01.ipynb diff --git a/book/09/asserts.ipynb b/book/errors/asserts.ipynb similarity index 100% rename from book/09/asserts.ipynb rename to book/errors/asserts.ipynb diff --git a/book/09/error_types.ipynb b/book/errors/error_types.ipynb similarity index 100% rename from book/09/error_types.ipynb rename to book/errors/error_types.ipynb diff --git a/book/09/handling_errors.ipynb b/book/errors/handling_errors.ipynb similarity index 100% rename from book/09/handling_errors.ipynb rename to book/errors/handling_errors.ipynb diff --git a/book/09/intro.md b/book/errors/intro.md similarity index 100% rename from book/09/intro.md rename to book/errors/intro.md diff --git a/book/09/raise_errors.ipynb b/book/errors/raise_errors.ipynb similarity index 100% rename from book/09/raise_errors.ipynb rename to book/errors/raise_errors.ipynb diff --git a/book/09/traceback.ipynb b/book/errors/traceback.ipynb similarity index 100% rename from book/09/traceback.ipynb rename to book/errors/traceback.ipynb diff --git a/book/numpy.md b/book/numpy.md new file mode 100644 index 0000000..35afd56 --- /dev/null +++ b/book/numpy.md @@ -0,0 +1,6 @@ +# Numpy + +This chapter is all about... + +% a short overview for this chapter + diff --git a/book/numpy/1d.ipynb b/book/numpy/1d.ipynb new file mode 100644 index 0000000..09d6008 --- /dev/null +++ b/book/numpy/1d.ipynb @@ -0,0 +1,794 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## One-Dimensional arrays" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ``np.array()``, ``np.asarray()``\n", + "So, how do you create a numpy 1-Dimensional (1D) array? There are a few ways to do it..." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Option 1 - from scratch with ``np.array()`` similar to a list." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr1 = [1 2 3], its type is \n" + ] + } + ], + "source": [ + "arr1 = np.array([1,2,3])\n", + "print('arr1 = {}, its type is {}'.format(arr1,type(arr1)))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Option 2 - from an existing list with ``np.array()``. \n", + "\n", + "Create the list first and check its type. Then create the array `A_1` from the list `L_1` and check its type." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "L_1 = [1, 2, 3, 5, 7, 11, 13] and its type is \n", + "\n", + "A_1 = [ 1 2 3 5 7 11 13] and its type is \n" + ] + } + ], + "source": [ + "L_1 = [1,2,3,5,7,11,13]\n", + "print('L_1 = {} and its type is {}\\n'.format(L_1,type(L_1)))\n", + "\n", + "A_1 = np.array(L_1)\n", + "print('A_1 = {} and its type is {}'.format(A_1, type(A_1)))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Option 3 - from an existing list with ``np.asarray()``" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "L_1 = [1, 2, 3, 5, 7, 11, 13] and its type is \n", + "\n", + "A_1 = [ 1 2 3 5 7 11 13] and its type is \n" + ] + } + ], + "source": [ + "L_1 = [1,2,3,5,7,11,13]\n", + "print('L_1 = {} and its type is {}\\n'.format(L_1,type(L_1)))\n", + "\n", + "A_1 = np.asarray(L_1)\n", + "print('A_1 = {} and its type is {}'.format(A_1, type(A_1)))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "From the above examples, you can't really determine the difference between using np.array() or np.asarray(). Nonetheless, there is a very important one, similar to the = and copy conundrum discussed in Notebook 4. When generating an array from a list, both functions do pretty much the same. However, when generating an array from another array, their differences stand out.\n", + "\n", + "First, let's check the ID of arr1" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr1 ID is 3116429230896\n" + ] + } + ], + "source": [ + "print('arr1 ID is {}'.format(id(arr1)))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, let's make two new arrays from arr1, using both functions" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr_array = [100 2 3] and its ID is 2342009211568\n", + "\n", + "arr_asarray = [100 2 3] and its ID is 2342276386128\n" + ] + } + ], + "source": [ + "arr_array = np.array(arr1)\n", + "arr_asarray = np.asarray(arr1)\n", + "\n", + "print('arr_array = {} and its ID is {}\\n'.format(arr_array,id(arr_array)))\n", + "print('arr_asarray = {} and its ID is {}'.format(arr_asarray, id(arr_asarray)))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "Hmm... it seems that the ID of arr_asarray is the same as the original arr1. Which means they are the same variable! Altering one will alter the other one as well. Let's try it out." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "ename": "ValueError", + "evalue": "invalid literal for int() with base 10: 'hello'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[8], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m arr1[\u001b[39m0\u001b[39m] \u001b[39m=\u001b[39m \u001b[39m'\u001b[39m\u001b[39mhello\u001b[39m\u001b[39m'\u001b[39m\n\u001b[0;32m 2\u001b[0m \u001b[39mprint\u001b[39m(arr_asarray)\n", + "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'hello'" + ] + } + ], + "source": [ + "arr1[0] = 'hello'\n", + "print(arr_asarray)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "Oops... it didn't work. Why do you think it didn't work?" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Answer: . . .\n", + "\n", + "Change the first element of `arr1`. Then print `arr_array` and `arr_asarray` to see if the first element changed." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr1 = [100 2 3]\n", + "\n", + "arr_array = [100 2 3]\n", + "\n", + "arr_asarray = [100 2 3]\n" + ] + } + ], + "source": [ + "arr1[0] = 100\n", + "\n", + "print('arr1 = {}\\n'.format(arr1))\n", + "print('arr_array = {}\\n'.format(arr_array))\n", + "print('arr_asarray = {}'.format(arr_asarray))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "Yep, our theory was right: arr1 and arr_asarray are indeed the same (but arr_array is not!). Therefore, altering arr1[0] will alter arr_asarray[0] in the same way.\n", + "\n", + "Final check that they are indeed the same" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "print(arr1 is arr_asarray)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "### ``np.zeros()``\n", + "In case you already know the size of the array you will need, it is common to initialize it with zeros first using the np.zeros() function, as shown below." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Set a limit when printing the huge arrays we will generate." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "tags": [ + "hide-input" + ] + }, + "outputs": [], + "source": [ + "np.set_printoptions(threshold=1) " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "I know I will need an array with 100000 elements so I create it full of zeros first. Then, I assign the values I need to each element.\n", + "in this example, I only wrote a `for` loop to assign random integer numbers between 0 and 9 to it. Note the use of `range(len(my_arr))`, we use this often to specify the range of the `for` loop to be of the same size as some array." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "my_arr with a bunch of zeros \n", + "[0. 0. 0. ... 0. 0. 0.]\n", + "\n", + "#######################\n", + "\n", + "my_arr with random numbers \n", + "[1. 0. 9. ... 7. 2. 4.]\n" + ] + } + ], + "source": [ + "\n", + "my_arr = np.zeros(100000)\n", + "print('my_arr with a bunch of zeros \\n{}\\n'.format(my_arr))\n", + "print('#######################')\n", + "\n", + "import random\n", + "\n", + "for i in range(len(my_arr)): \n", + " my_arr[i] = random.randint(0,9)\n", + " \n", + "print('\\nmy_arr with random numbers \\n{}'.format(my_arr))\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "Note that these arrays still have $100000$ elements, but due to our first line of code we truncated the print function to not print it completely — otherwise you would have to scroll a lot. :P " + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "### ``np.min()``, ``np.max()`` and ``np.mean()``\n", + "\n", + "Numpy also provides various packages to help you process your data. You can, for instance, find out what is the minimum value of an array, or its mean. Your task is to find the minimum, maximum, and mean values of an array.\n", + "\n", + "Find the minimum, maximum and mean values of A_1 and print the results." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The minimum value of A_1 is 1 \n", + "\n", + "The maximum value of A_1 is 13 \n", + "\n", + "The mean value of A_1 is 6.0 \n", + "\n" + ] + } + ], + "source": [ + "A_1_min = np.min(A_1)\n", + "A_1_max = np.max(A_1)\n", + "A_1_mean = np.mean(A_1)\n", + "\n", + "print(f'The minimum value of A_1 is {A_1_min} \\n')\n", + "print(f'The maximum value of A_1 is {A_1_max} \\n')\n", + "print(f'The mean value of A_1 is {A_1_mean} \\n')" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ``np.arange()``\n", + "\n", + "Another useful function of the numpy module is np.arange(). First, let's see in the documentation what it does." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It reads:

arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.


To make a number range you need to choose:
1) the starting point,
2) the endpoint,
3) the interval between each point

The reason why it reads [start,] stop[, step,] with square brackets, is that the start and the step can be omitted. If not specified, start = 0 and step = 1, by default." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "::: {warning}\n", + "Your endpoint is not included in the array. If you want to include the endpoint in the array, you have to specify the stop to be endpoint + step. This will be clearer in the following examples.\n", + ":::" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "omitted start and step" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr = [0 1 2 3 4]\n" + ] + } + ], + "source": [ + "arr = np.arange(5) \n", + "print('arr =', arr)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As mentioned, the endpoint (5) is omitted. If you would like to include it:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr = [0 1 2 3 4 5]\n" + ] + } + ], + "source": [ + "arr = np.arange(5 + 1)\n", + "print('arr =', arr)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, without omiting `start` nor `step`. Without endpoint." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr = [1. 1.01 1.02 ... 1.97 1.98 1.99]\n" + ] + } + ], + "source": [ + "arr = np.arange(1, 2, 0.01)\n", + "print('arr =', arr)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Including endpoint" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr = [1. 1.01 1.02 ... 1.98 1.99 2. ]\n" + ] + } + ], + "source": [ + "arr = np.arange(1, 2 + 0.01, 0.01) \n", + "print('arr =', arr)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also generate a descending array, by using negative steps" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "arr = [10 9 8 ... 3 2 1]\n" + ] + } + ], + "source": [ + "arr = np.arange(10,0,-1)\n", + "print('arr =', arr)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ``np.sort()``\n", + "\n", + "You can also sort an array in the crescent order using np.sort()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "sorted_arr = [ 1 2 3 ... 8 9 10]\n" + ] + } + ], + "source": [ + "sorted_arr = np.sort(arr)\n", + "print('sorted_arr =', sorted_arr)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ``np.sum()``\n", + "\n", + "As the name clearly states, np.sum() returns the sum of an array. Let's try it out:" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The sum of the array is 6\n" + ] + } + ], + "source": [ + "arr = ([1,2,3])\n", + "my_sum = np.sum(arr)\n", + "print(f'The sum of the array is {my_sum}')" + ] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "mude", + "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.11.9" + }, + "latex_envs": { + "LaTeX_envs_menu_present": true, + "autoclose": false, + "autocomplete": true, + "bibliofile": "biblio.bib", + "cite_by": "apalike", + "current_citInitial": 1, + "eqLabelWithNumbers": true, + "eqNumInitial": 1, + "hotkeys": { + "equation": "Ctrl-E", + "itemize": "Ctrl-I" + }, + "labels_anchors": false, + "latex_user_defs": false, + "report_style_numbering": false, + "user_envs_cfg": 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 +} diff --git a/book/05/Theory/01.ipynb b/book/numpy/2d.ipynb similarity index 62% rename from book/05/Theory/01.ipynb rename to book/numpy/2d.ipynb index 7a0a991..dc92c74 100644 --- a/book/05/Theory/01.ipynb +++ b/book/numpy/2d.ipynb @@ -1,37 +1,5 @@ { "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "# 5. Numpy" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "## 5.1. Introduction\n", - "\n", - "The numpy package is one of the main packages when it comes to working with arrays and matrices in Python, making it indispensable to process and visualize scientific data. Its assortment of routines facilitates operations such as mathematical, logical, linear algebra, Fourier transforms, and much more. In this section, you will learn some of the most used numpy functions to work with multidimensional array objects.\n", - "\n", - "As always, let's import the package we will use" - ] - }, { "cell_type": "code", "execution_count": 1, @@ -59,761 +27,7 @@ } }, "source": [ - "The following functions will be discussed in this Notebook:\n", - "- np.array() \n", - "- np.zeros() \n", - "- np.asarray() \n", - "- np.shape()\n", - "- np.min()\n", - "- np.max()\n", - "- np.mean()\n", - "- np.sort()\n", - "- np.linspace()\n", - "- np.arange()\n", - "- np.argmax()\n", - "- np.argmin()\n", - "- np.where()\n", - "- np.astype()\n", - "- np.dot()\n", - "- np.transpose()\n", - "- np.loadtxt()\n", - "- np.sum()\n", - "- np.cos()\n", - "- np.sin()\n", - "- np.sqrt()\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "In Section 2.3, of Notebook 2, you have already encountered lists, which are created with square brackets []. Arrays are the numpy equivalent of lists, with a few characteristic traits:

- numpy arrays can only store one type of element,
- numpy arrays take up much less memory than lists,
- numpy arrays have a much better runtime behavior,
- it is easier to work with multi-dimensional numpy arrays than with multi-dimensional lists

" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 5.2 One-Dimensional arrays" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ``np.array()``, ``np.asarray()``\n", - "So, how do you create a numpy 1-Dimensional (1D) array? There are a few ways to do it..." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Option 1 - from scratch with ``np.array()`` similar to a list." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr1 = [1 2 3], its type is \n" - ] - } - ], - "source": [ - "arr1 = np.array([1,2,3])\n", - "print('arr1 = {}, its type is {}'.format(arr1,type(arr1)))" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Option 2 - from an existing list with ``np.array()``. \n", - "\n", - "Create the list first and check its type. Then create the array `A_1` from the list `L_1` and check its type." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "L_1 = [1, 2, 3, 5, 7, 11, 13] and its type is \n", - "\n", - "A_1 = [ 1 2 3 5 7 11 13] and its type is \n" - ] - } - ], - "source": [ - "L_1 = [1,2,3,5,7,11,13]\n", - "print('L_1 = {} and its type is {}\\n'.format(L_1,type(L_1)))\n", - "\n", - "A_1 = np.array(L_1)\n", - "print('A_1 = {} and its type is {}'.format(A_1, type(A_1)))" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Option 3 - from an existing list with ``np.asarray()``" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "L_1 = [1, 2, 3, 5, 7, 11, 13] and its type is \n", - "\n", - "A_1 = [ 1 2 3 5 7 11 13] and its type is \n" - ] - } - ], - "source": [ - "L_1 = [1,2,3,5,7,11,13]\n", - "print('L_1 = {} and its type is {}\\n'.format(L_1,type(L_1)))\n", - "\n", - "A_1 = np.asarray(L_1)\n", - "print('A_1 = {} and its type is {}'.format(A_1, type(A_1)))" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "From the above examples, you can't really determine the difference between using np.array() or np.asarray(). Nonetheless, there is a very important one, similar to the = and copy conundrum discussed in Notebook 4. When generating an array from a list, both functions do pretty much the same. However, when generating an array from another array, their differences stand out.\n", - "\n", - "First, let's check the ID of arr1" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr1 ID is 3116429230896\n" - ] - } - ], - "source": [ - "print('arr1 ID is {}'.format(id(arr1)))" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now, let's make two new arrays from arr1, using both functions" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr_array = [100 2 3] and its ID is 2342009211568\n", - "\n", - "arr_asarray = [100 2 3] and its ID is 2342276386128\n" - ] - } - ], - "source": [ - "arr_array = np.array(arr1)\n", - "arr_asarray = np.asarray(arr1)\n", - "\n", - "print('arr_array = {} and its ID is {}\\n'.format(arr_array,id(arr_array)))\n", - "print('arr_asarray = {} and its ID is {}'.format(arr_asarray, id(arr_asarray)))" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "Hmm... it seems that the ID of arr_asarray is the same as the original arr1. Which means they are the same variable! Altering one will alter the other one as well. Let's try it out." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "ename": "ValueError", - "evalue": "invalid literal for int() with base 10: 'hello'", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", - "Cell \u001b[1;32mIn[8], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m arr1[\u001b[39m0\u001b[39m] \u001b[39m=\u001b[39m \u001b[39m'\u001b[39m\u001b[39mhello\u001b[39m\u001b[39m'\u001b[39m\n\u001b[0;32m 2\u001b[0m \u001b[39mprint\u001b[39m(arr_asarray)\n", - "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'hello'" - ] - } - ], - "source": [ - "arr1[0] = 'hello'\n", - "print(arr_asarray)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "Oops... it didn't work. Why do you think it didn't work?" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Answer: . . .\n", - "\n", - "Change the first element of `arr1`. Then print `arr_array` and `arr_asarray` to see if the first element changed." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr1 = [100 2 3]\n", - "\n", - "arr_array = [100 2 3]\n", - "\n", - "arr_asarray = [100 2 3]\n" - ] - } - ], - "source": [ - "arr1[0] = 100\n", - "\n", - "print('arr1 = {}\\n'.format(arr1))\n", - "print('arr_array = {}\\n'.format(arr_array))\n", - "print('arr_asarray = {}'.format(arr_asarray))" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "Yep, our theory was right: arr1 and arr_asarray are indeed the same (but arr_array is not!). Therefore, altering arr1[0] will alter arr_asarray[0] in the same way.\n", - "\n", - "Final check that they are indeed the same" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "True\n" - ] - } - ], - "source": [ - "print(arr1 is arr_asarray)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "### ``np.zeros()``\n", - "In case you already know the size of the array you will need, it is common to initialize it with zeros first using the np.zeros() function, as shown below." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Set a limit when printing the huge arrays we will generate." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "tags": [ - "hide-input" - ] - }, - "outputs": [], - "source": [ - "np.set_printoptions(threshold=1) " - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "I know I will need an array with 100000 elements so I create it full of zeros first. Then, I assign the values I need to each element.\n", - "in this example, I only wrote a `for` loop to assign random integer numbers between 0 and 9 to it. Note the use of `range(len(my_arr))`, we use this often to specify the range of the `for` loop to be of the same size as some array." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "collapsed": true, - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "my_arr with a bunch of zeros \n", - "[0. 0. 0. ... 0. 0. 0.]\n", - "\n", - "#######################\n", - "\n", - "my_arr with random numbers \n", - "[1. 0. 9. ... 7. 2. 4.]\n" - ] - } - ], - "source": [ - "\n", - "my_arr = np.zeros(100000)\n", - "print('my_arr with a bunch of zeros \\n{}\\n'.format(my_arr))\n", - "print('#######################')\n", - "\n", - "import random\n", - "\n", - "for i in range(len(my_arr)): \n", - " my_arr[i] = random.randint(0,9)\n", - " \n", - "print('\\nmy_arr with random numbers \\n{}'.format(my_arr))\n" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "Note that these arrays still have $100000$ elements, but due to our first line of code we truncated the print function to not print it completely — otherwise you would have to scroll a lot. :P " - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "### ``np.min()``, ``np.max()`` and ``np.mean()``\n", - "\n", - "Numpy also provides various packages to help you process your data. You can, for instance, find out what is the minimum value of an array, or its mean. Your task is to find the minimum, maximum, and mean values of an array.\n", - "\n", - "Find the minimum, maximum and mean values of A_1 and print the results." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The minimum value of A_1 is 1 \n", - "\n", - "The maximum value of A_1 is 13 \n", - "\n", - "The mean value of A_1 is 6.0 \n", - "\n" - ] - } - ], - "source": [ - "A_1_min = np.min(A_1)\n", - "A_1_max = np.max(A_1)\n", - "A_1_mean = np.mean(A_1)\n", - "\n", - "print(f'The minimum value of A_1 is {A_1_min} \\n')\n", - "print(f'The maximum value of A_1 is {A_1_max} \\n')\n", - "print(f'The mean value of A_1 is {A_1_mean} \\n')" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ``np.arange()``\n", - "\n", - "Another useful function of the numpy module is np.arange(). First, let's see in the documentation what it does." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It reads:

arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval.


To make a number range you need to choose:
1) the starting point,
2) the endpoint,
3) the interval between each point

The reason why it reads [start,] stop[, step,] with square brackets, is that the start and the step can be omitted. If not specified, start = 0 and step = 1, by default." - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "::: {warning}\n", - "Your endpoint is not included in the array. If you want to include the endpoint in the array, you have to specify the stop to be endpoint + step. This will be clearer in the following examples.\n", - ":::" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "omitted start and step" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr = [0 1 2 3 4]\n" - ] - } - ], - "source": [ - "arr = np.arange(5) \n", - "print('arr =', arr)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As mentioned, the endpoint (5) is omitted. If you would like to include it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr = [0 1 2 3 4 5]\n" - ] - } - ], - "source": [ - "arr = np.arange(5 + 1)\n", - "print('arr =', arr)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now, without omiting `start` nor `step`. Without endpoint." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr = [1. 1.01 1.02 ... 1.97 1.98 1.99]\n" - ] - } - ], - "source": [ - "arr = np.arange(1, 2, 0.01)\n", - "print('arr =', arr)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Including endpoint" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr = [1. 1.01 1.02 ... 1.98 1.99 2. ]\n" - ] - } - ], - "source": [ - "arr = np.arange(1, 2 + 0.01, 0.01) \n", - "print('arr =', arr)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also generate a descending array, by using negative steps" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "arr = [10 9 8 ... 3 2 1]\n" - ] - } - ], - "source": [ - "arr = np.arange(10,0,-1)\n", - "print('arr =', arr)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ``np.sort()``\n", - "\n", - "You can also sort an array in the crescent order using np.sort()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "sorted_arr = [ 1 2 3 ... 8 9 10]\n" - ] - } - ], - "source": [ - "sorted_arr = np.sort(arr)\n", - "print('sorted_arr =', sorted_arr)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ``np.sum()``\n", - "\n", - "As the name clearly states, np.sum() returns the sum of an array. Let's try it out:" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The sum of the array is 6\n" - ] - } - ], - "source": [ - "arr = ([1,2,3])\n", - "my_sum = np.sum(arr)\n", - "print(f'The sum of the array is {my_sum}')" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": { - "nbgrader": { - "grade": false, - "locked": true, - "solution": false - } - }, - "source": [ - "## 5.3 Two-Dimensional arrays and matrices\n", + "## Two-Dimensional arrays and matrices\n", "\n", "As mentioned earlier, numpy is not solely built for 1D arrays $-$ it's built to work with multidimensional arrays! So, let's hop into 2D arrays and matrices, which you have already encountered in Linear Algebra. You can construct your own matrix using the np.array() function, as shown below." ] diff --git a/book/05/Exercises/01.ipynb b/book/numpy/Exercises/01.ipynb similarity index 100% rename from book/05/Exercises/01.ipynb rename to book/numpy/Exercises/01.ipynb diff --git a/book/05/Exercises/01.json b/book/numpy/Exercises/01.json similarity index 100% rename from book/05/Exercises/01.json rename to book/numpy/Exercises/01.json diff --git a/book/05/Exercises/02.ipynb b/book/numpy/Exercises/02.ipynb similarity index 100% rename from book/05/Exercises/02.ipynb rename to book/numpy/Exercises/02.ipynb diff --git a/book/05/Exercises/02.json b/book/numpy/Exercises/02.json similarity index 100% rename from book/05/Exercises/02.json rename to book/numpy/Exercises/02.json diff --git a/book/05/Exercises/02_01.csv b/book/numpy/Exercises/02_01.csv similarity index 100% rename from book/05/Exercises/02_01.csv rename to book/numpy/Exercises/02_01.csv diff --git a/book/05/Exercises/02_01.png b/book/numpy/Exercises/02_01.png similarity index 100% rename from book/05/Exercises/02_01.png rename to book/numpy/Exercises/02_01.png diff --git a/book/numpy/introduction.ipynb b/book/numpy/introduction.ipynb new file mode 100644 index 0000000..a45ea2d --- /dev/null +++ b/book/numpy/introduction.ipynb @@ -0,0 +1,156 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "## Introduction\n", + "\n", + "The numpy package is one of the main packages when it comes to working with arrays and matrices in Python, making it indispensable to process and visualize scientific data. Its assortment of routines facilitates operations such as mathematical, logical, linear algebra, Fourier transforms, and much more. In this section, you will learn some of the most used numpy functions to work with multidimensional array objects.\n", + "\n", + "As always, let's import the package we will use" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true, + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "The following functions will be discussed in this Notebook:\n", + "- np.array() \n", + "- np.zeros() \n", + "- np.asarray() \n", + "- np.shape()\n", + "- np.min()\n", + "- np.max()\n", + "- np.mean()\n", + "- np.sort()\n", + "- np.linspace()\n", + "- np.arange()\n", + "- np.argmax()\n", + "- np.argmin()\n", + "- np.where()\n", + "- np.astype()\n", + "- np.dot()\n", + "- np.transpose()\n", + "- np.loadtxt()\n", + "- np.sum()\n", + "- np.cos()\n", + "- np.sin()\n", + "- np.sqrt()\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": { + "nbgrader": { + "grade": false, + "locked": true, + "solution": false + } + }, + "source": [ + "In Section 2.3, of Notebook 2, you have already encountered lists, which are created with square brackets []. Arrays are the numpy equivalent of lists, with a few characteristic traits:

- numpy arrays can only store one type of element,
- numpy arrays take up much less memory than lists,
- numpy arrays have a much better runtime behavior,
- it is easier to work with multi-dimensional numpy arrays than with multi-dimensional lists

" + ] + } + ], + "metadata": { + "hide_input": false, + "kernelspec": { + "display_name": "mude", + "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.11.9" + }, + "latex_envs": { + "LaTeX_envs_menu_present": true, + "autoclose": false, + "autocomplete": true, + "bibliofile": "biblio.bib", + "cite_by": "apalike", + "current_citInitial": 1, + "eqLabelWithNumbers": true, + "eqNumInitial": 1, + "hotkeys": { + "equation": "Ctrl-E", + "itemize": "Ctrl-I" + }, + "labels_anchors": false, + "latex_user_defs": false, + "report_style_numbering": false, + "user_envs_cfg": 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 +} diff --git a/book/numpy/nutshell.md b/book/numpy/nutshell.md new file mode 100644 index 0000000..8ad5df1 --- /dev/null +++ b/book/numpy/nutshell.md @@ -0,0 +1,3 @@ +# Numpy: in a Nutshell + +Nutshell. \ No newline at end of file diff --git a/book/05/In_a_Nutshell/01.ipynb b/book/numpy/nutshell/numpy.ipynb similarity index 100% rename from book/05/In_a_Nutshell/01.ipynb rename to book/numpy/nutshell/numpy.ipynb