Arrays in Python.ipynb 34.3 KB
Newer Older
1 2
{
 "cells": [
James Sutherland's avatar
James Sutherland committed
3 4 5 6 7 8 9 10 11 12
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": "true"
   },
   "source": [
    "# Table of Contents\n",
    " <p><div class=\"lev1 toc-item\"><a href=\"#Arrays-in-Python\" data-toc-modified-id=\"Arrays-in-Python-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Arrays in Python</a></div><div class=\"lev2 toc-item\"><a href=\"#Overview\" data-toc-modified-id=\"Overview-11\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>Overview</a></div><div class=\"lev1 toc-item\"><a href=\"#Lists\" data-toc-modified-id=\"Lists-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Lists</a></div><div class=\"lev2 toc-item\"><a href=\"#Operations-on-Lists\" data-toc-modified-id=\"Operations-on-Lists-21\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>Operations on Lists</a></div><div class=\"lev2 toc-item\"><a href=\"#Indexing-and-Slicing-Lists\" data-toc-modified-id=\"Indexing-and-Slicing-Lists-22\"><span class=\"toc-item-num\">2.2&nbsp;&nbsp;</span>Indexing and Slicing Lists</a></div><div class=\"lev2 toc-item\"><a href=\"#Loops-and-Lists\" data-toc-modified-id=\"Loops-and-Lists-23\"><span class=\"toc-item-num\">2.3&nbsp;&nbsp;</span>Loops and Lists</a></div><div class=\"lev3 toc-item\"><a href=\"#Iterating-a-list\" data-toc-modified-id=\"Iterating-a-list-231\"><span class=\"toc-item-num\">2.3.1&nbsp;&nbsp;</span>Iterating a list</a></div><div class=\"lev3 toc-item\"><a href=\"#Index-loops\" data-toc-modified-id=\"Index-loops-232\"><span class=\"toc-item-num\">2.3.2&nbsp;&nbsp;</span>Index loops</a></div><div class=\"lev3 toc-item\"><a href=\"#List-comprehensions\" data-toc-modified-id=\"List-comprehensions-233\"><span class=\"toc-item-num\">2.3.3&nbsp;&nbsp;</span>List comprehensions</a></div><div class=\"lev1 toc-item\"><a href=\"#Tuples\" data-toc-modified-id=\"Tuples-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Tuples</a></div><div class=\"lev1 toc-item\"><a href=\"#Numpy-Arrays\" data-toc-modified-id=\"Numpy-Arrays-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Numpy Arrays</a></div><div class=\"lev2 toc-item\"><a href=\"#Constructing-Numpy-Arrays\" data-toc-modified-id=\"Constructing-Numpy-Arrays-41\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Constructing Numpy Arrays</a></div><div class=\"lev3 toc-item\"><a href=\"#Data-Types\" data-toc-modified-id=\"Data-Types-411\"><span class=\"toc-item-num\">4.1.1&nbsp;&nbsp;</span>Data Types</a></div><div class=\"lev4 toc-item\"><a href=\"#Example\" data-toc-modified-id=\"Example-4111\"><span class=\"toc-item-num\">4.1.1.1&nbsp;&nbsp;</span>Example</a></div><div class=\"lev3 toc-item\"><a href=\"#Arrays-over-specified-ranges\" data-toc-modified-id=\"Arrays-over-specified-ranges-412\"><span class=\"toc-item-num\">4.1.2&nbsp;&nbsp;</span>Arrays over specified ranges</a></div><div class=\"lev3 toc-item\"><a href=\"#Other-Constructors\" data-toc-modified-id=\"Other-Constructors-413\"><span class=\"toc-item-num\">4.1.3&nbsp;&nbsp;</span>Other Constructors</a></div><div class=\"lev2 toc-item\"><a href=\"#Numpy-Matrices\" data-toc-modified-id=\"Numpy-Matrices-42\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>Numpy Matrices</a></div><div class=\"lev2 toc-item\"><a href=\"#Manipulating-Numpy-Arrays\" data-toc-modified-id=\"Manipulating-Numpy-Arrays-43\"><span class=\"toc-item-num\">4.3&nbsp;&nbsp;</span>Manipulating Numpy Arrays</a></div><div class=\"lev3 toc-item\"><a href=\"#Indexing-and-Slicing\" data-toc-modified-id=\"Indexing-and-Slicing-431\"><span class=\"toc-item-num\">4.3.1&nbsp;&nbsp;</span>Indexing and Slicing</a></div><div class=\"lev1 toc-item\"><a href=\"#Mathematical-Operations-on-Numpy-Arrays\" data-toc-modified-id=\"Mathematical-Operations-on-Numpy-Arrays-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Mathematical Operations on Numpy Arrays</a></div><div class=\"lev2 toc-item\"><a href=\"#Array-Multiplication\" data-toc-modified-id=\"Array-Multiplication-51\"><span class=\"toc-item-num\">5.1&nbsp;&nbsp;</span>Array Multiplication</a></div><div class=\"lev3 toc-item\"><a href=\"#Elemental-Multiplication\" data-toc-modified-id=\"Elemental-Multiplication-511\"><span class=\"toc-item-num\">5.1.1&nbsp;&nbsp;</span>Elemental Multiplication</a></div><div class=\"lev3 toc-item\"><a href=\"#Matrix-Multiplication\" data-toc-modified-id=\"Matrix-Multiplication-512\"><span class=\"toc-item-num\">5.1.2&nbsp;&nbsp;</span>Matrix Multiplication</a></div><div class=\"lev2 toc-item\"><a href=\"#More-useful-stuff\" data-toc-modified-id=\"More-useful-stuff-52\"><span class=\"toc-item-num\">5.2&nbsp;&nbsp;</span>More useful stuff</a></div><div class=\"lev1 toc-item\"><a href=\"#Masking-Numpy-Arrays\" data-toc-modified-id=\"Masking-Numpy-Arrays-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Masking Numpy Arrays</a></div>"
   ]
  },
13 14
  {
   "cell_type": "markdown",
15 16 17 18 19
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
20
   "source": [
James Sutherland's avatar
James Sutherland committed
21
    "![Chemical Engineering Logo](https://sutherland.che.utah.edu/Chem-Engingeering_combined-hrz.jpg)\n",
22
    "\n",
23 24 25 26 27 28
    "----\n",
    "# Arrays in Python\n",
    "\n",
    "Contributors:\n",
    " * [James C. Sutherland](sutherland.che.utah.edu)\n",
    "\n",
29 30 31 32 33 34 35 36 37 38 39 40
    "----"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
James Sutherland's avatar
James Sutherland committed
41
    "\n",
42 43 44
    "__Note__: if you are a matlab user, you may want to look at\n",
    "  * This [great cheat sheet](http://mathesaurus.sourceforge.net/matlab-python-xref.pdf) showing common matlab commands and their python counterparts\n",
    "  * [Numpy for matlab users](http://mathesaurus.sourceforge.net/matlab-numpy.html)"
45 46 47 48
   ]
  },
  {
   "cell_type": "markdown",
49 50 51 52 53
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
54 55 56
   "source": [
    "## Overview\n",
    "In python, there are a few ways to manage collections of information:\n",
James Sutherland's avatar
James Sutherland committed
57
    "  * A [`list`](#Lists) is built-in to the language, and can contain any type\n",
58
    "  * A [`tuple`](#Tuples) is also built-in to the language, and is similar to a list, but is immutable.\n",
59
    "  * A [numpy array](#Numpy-Arrays) is provided by the [`numpy`](https://docs.scipy.org/doc/numpy/reference) package in python and is useful for holding collections of numbers."
60 61 62 63
   ]
  },
  {
   "cell_type": "markdown",
64 65 66 67 68
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
69 70
   "source": [
    "# Lists\n",
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    "A _list_ in python is enclosed by square brackets, and can contain any types (including other lists):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 'a string', 5, 3.14, [1, 2, 3, 4], ['apple', 'banana', 'orange']]\n",
      "4\n",
      "5\n"
     ]
    }
   ],
   "source": [
90 91 92 93 94 95 96 97 98 99 100 101
    "# A list of integers:\n",
    "x = [1,2,3,4]\n",
    "\n",
    "# A list of strings:\n",
    "fruits = ['apple','banana','orange']\n",
    "\n",
    "# A list of many things, including other lists!\n",
    "my_list = [ 2, 'a string', 5, 3.14, x, fruits ]\n",
    "\n",
    "print(my_list)\n",
    "\n",
    "print(my_list.index(x))  # find where x appears (4)\n",
102
    "print(my_list[2])        # 5"
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "You can think of a list in python as an array in Matlab, C/C++, Fortran, etc.  The primary difference is that, in Python, a list can have different types (strings, integeres, etc.) in the same list/array."
   ]
  },
  {
   "cell_type": "markdown",
118 119
   "metadata": {},
   "source": [
120
    "<div class=\"alert alert-block alert-warning\">\n",
James Sutherland's avatar
James Sutherland committed
121
    "\n",
122 123 124 125 126 127
    "___Caution___: copying arrays in python is unique:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
James Sutherland's avatar
James Sutherland committed
128
   "metadata": {},
129
   "outputs": [],
130
   "source": [
131
    "a = [1,2,3]\n",
132
    "b = a"
133 134 135 136
   ]
  },
  {
   "cell_type": "markdown",
137 138 139 140 141 142 143 144
   "metadata": {},
   "source": [
    "makes `b` alias to `a`.  This means that"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
James Sutherland's avatar
James Sutherland committed
145
   "metadata": {},
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
   "outputs": [],
   "source": [
    "b[1]=5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "also changes `a[1]` to 5:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 5, 3] [1, 5, 3]\n"
     ]
    }
   ],
   "source": [
    "print(a,b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To make a full copy of an array, use the `copy` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
185 186
   "metadata": {
    "slideshow": {
187
     "slide_type": "subslide"
188 189
    }
   },
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 5, 3] [1, 5, 3] [1, 5, 19]\n"
     ]
    }
   ],
   "source": [
    "b = a         # b and a are the same array\n",
    "c = a.copy()  # c and a are different arrays with the same contents\n",
    "c[2] = 19\n",
    "print(a,b,c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
   "source": [
    "## Operations on Lists\n",
    "Frequently we want to perform operations on lists\n",
    "\n",
    "Method | Description | Example\n",
    ":--- | :--- | :---\n",
    "`len` | Returns the number of entries in the list | `len(my_list)`\n",
    "`append(entry)` | Append an entry to the list | `my_list.append( 'another entry' )`\n",
    "`insert(index,entry)` | Insert an entry in the list | `my_list.insert(2,10)`\n",
    "`extend(list2)` | append a list | `my_list.append( ('a','b',x) )`\n",
    "`+` | append a list (same as `extend`) | `my_list + my_list`\n",
    "`remove(entry)` | Append an entry to the list | `my_list.remove( x )`\n",
    "`sort()` | sort the list - only works when the list is homogeneous | `x.sort()`\n",
    "`reverse()` | reverses the entries in the list | `my_list.reverse()`\n",
    "`pop(index)` | return and remove the element in the list at `index` | `my_list.pop(3)`\n",
    "`count(entry)` | return the number of occurences of `entry` in the list | `my_list.count(2)`\n",
225
    "`index(entry)` | return the index at which the first occurence of `entry` occurs | `my_list.index(x)`"
226 227 228 229
   ]
  },
  {
   "cell_type": "markdown",
230 231 232 233 234 235 236 237
   "metadata": {},
   "source": [
    "You can also use the keyword `in` with a list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
238 239 240 241 242
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Yes!\n"
     ]
    }
   ],
   "source": [
    "fruits = ['apple','pear','banana','payapa']\n",
    "if 'banana' in fruits:\n",
    "    print('Yes!')\n",
    "else:\n",
    "    print('No!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
263 264 265
   "source": [
    "## Indexing and Slicing Lists\n",
    "\n",
266 267 268 269 270 271
    "Indexing a list is done with the `[]` operator, and is 0-based (0 indicates the first entry in the list).  For example, given:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
James Sutherland's avatar
James Sutherland committed
272
   "metadata": {},
273 274 275 276 277 278 279 280 281
   "outputs": [],
   "source": [
    "fruits = ['apple','banana','grapefruit','orange']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
282 283 284 285 286 287 288 289 290 291
    "the following table shows various indexing operations:\n",
    "\n",
    "Operation | Result | Description\n",
    ":--- | :--- | :---\n",
    "`fruits[1]` | `banana` | Accesses the second element in the list\n",
    "`fruits[-1]` | `orange` | Accesses the last element in the list\n",
    "`fruits[-2]` | `grapefruit` | Accesses the second to last element in the list\n",
    "`fruits[:2]` | `[apple,banana]` | The first two elements in the list\n",
    "`fruits[1:2]`| `[banana,grapefruit]` | The second and third elements in the list\n",
    "\n",
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    "The `:` operator allows us to perform _slicing_, accessing a subset of the entries in a list."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also use slicing to replace elements of a list.  For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
320 321 322 323
    "x = [1,2,3,4]\n",
    "y = x[1:3]\n",
    "y.reverse()\n",
    "x[0:2] = y\n",
324
    "print(x)"
325 326 327 328
   ]
  },
  {
   "cell_type": "markdown",
329 330 331 332 333
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
334 335
   "source": [
    "## Loops and Lists\n",
336 337 338 339 340
    "There are a few ways to loop over lists.  This is perhaps best illustrated by a few examples."
   ]
  },
  {
   "cell_type": "markdown",
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
   "metadata": {},
   "source": [
    "### Iterating a list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apple\n",
      "banana\n",
      "orange\n"
     ]
359
    }
360
   ],
361
   "source": [
362 363
    "fruits = ['apple','banana','orange']\n",
    "for i in fruits:\n",
364
    "    print(i)"
365 366 367 368 369 370 371 372 373
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
374 375 376 377 378 379 380
   "source": [
    "Here, `i` is an _iterator_ that represents each entry in the list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
381
   "source": [
382
    "### Index loops\n",
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    "Here we use the `range()` function, which builds a range space for the loop. This allows us to use `i` as an index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fruit 0 = apple\n",
      "Fruit 1 = banana\n",
      "Fruit 2 = orange\n"
     ]
    }
   ],
   "source": [
402 403
    "fruits = ['apple','banana','orange']\n",
    "for i in range(0,len(fruits)):\n",
404
    "    print('Fruit {} = {}'.format(i,fruits[i]))"
405 406 407 408 409 410 411 412 413
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
414
   "source": [
415
    "<div class=\"alert alert-block alert-info\">\n",
James Sutherland's avatar
James Sutherland committed
416
    "\n",
417
    "`range(lo,hi)` creates a range of integers from __`lo`__ to __`hi-1`__"
418 419 420 421 422
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
423
   "source": [
424 425 426
    "### List comprehensions\n",
    "List comprehensions can be used to quickly build lists conforming to specific patterns.  For example, if we wanted to build a list \n",
    "$$x_i=i^2, \\quad i=1\\ldots4$$\n",
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    "we can do this by:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9]\n"
     ]
    }
   ],
   "source": [
444
    "x = [i**2 for i in range(1,4)]\n",
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, to achieve $y_i=2^i, \\; i=1\\ldots 8$, we can do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 4, 8, 16, 32, 64, 128, 256]\n"
     ]
    }
   ],
   "source": [
    "y = [2**i for i in range(1,9)]\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
481
    "List comprehensions provide a relatively simple syntax to build these types of lists."
482 483 484 485
   ]
  },
  {
   "cell_type": "markdown",
486 487 488 489 490
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
491 492 493 494 495 496 497 498 499 500 501 502 503
   "source": [
    "# Tuples\n",
    "In python, a _tuple_ is like a list, but has a few differences:\n",
    " * It is declared using `()` rather than `[]`\n",
    " * It is immutable - it cannot be changed once it is built\n",
    " \n",
    "Elements in a tuple are accessed in the same way as lists, using the `[]` operator.\n",
    "\n",
    "Generally, you will use lists rather than tuples."
   ]
  },
  {
   "cell_type": "markdown",
504 505 506 507 508
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
509 510 511 512 513 514 515 516
   "source": [
    "---\n",
    "# Numpy Arrays\n",
    "The list functionality in python is not as useful as it could be when it comes to numerical operations.  For example, you cannot perform mathematical operations on lists.\n",
    "This is where [numpy](https://docs.scipy.org/doc/numpy/reference/) comes in.\n",
    "\n",
    "Unlike a Python list, a Numpy arrays is _homogeneous_ - they contain entries of the same type (e.g., integer, real, complex).\n",
    "\n",
517 518 519 520 521 522 523
    "Here and below, we will assume that you have:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
524 525 526
    "slideshow": {
     "slide_type": "fragment"
    }
527 528 529 530
   },
   "outputs": [],
   "source": [
    "import numpy as np"
531 532 533 534
   ]
  },
  {
   "cell_type": "markdown",
535 536
   "metadata": {
    "slideshow": {
537
     "slide_type": "fragment"
538 539
    }
   },
540 541 542 543 544 545
   "source": [
    "so that we can use __`np.`__ to shorten reference to numpy functions."
   ]
  },
  {
   "cell_type": "markdown",
546 547 548 549 550
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
551 552
   "source": [
    "## Constructing Numpy Arrays\n",
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    "A numpy array is characterized by its _shape_ and the type of elements it contains."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3,) [1 2 3]\n",
      "(2, 3) [[1 2 3]\n",
      " [4 5 6]]\n"
     ]
    }
   ],
   "source": [
576 577 578
    "x = np.array( [1,2,3] )             # a 1-dimensional row vector\n",
    "y = np.array( [ [1,2,3],[4,5,6] ] ) # a 2-dimensional matrix\n",
    "print(x.shape,x)\n",
579
    "print(y.shape,y)"
580 581 582 583 584 585 586 587 588 589 590
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Data Types\n",
591 592 593 594 595 596 597 598 599
    "You can explicitly specify the [type of the data](https://docs.scipy.org/doc/numpy-1.12.0/reference/arrays.dtypes.html#specifying-and-constructing-data-types) in the array.  Here are some of the common types you will use:\n",
    "\n",
    "Keyword | Description\n",
    ":---|:---\n",
    "[int](https://docs.python.org/dev/library/functions.html#int) | Integer\n",
    "[bool](https://docs.python.org/dev/library/functions.html#bool) | boolean (True/False)\n",
    "[float](https://docs.python.org/dev/library/functions.html#float) | Floating point (real)\n",
    "[complex](https://docs.python.org/dev/library/functions.html#complex) | Complex numbers\n",
    "[string](https://docs.python.org/dev/library/stdtypes.html#str) | string\n",
600 601 602
    "(other) | User-defined data types"
   ]
  },
603 604
  {
   "cell_type": "markdown",
605 606 607 608 609
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
610 611 612 613
   "source": [
    "#### Example"
   ]
  },
614 615 616 617 618 619 620 621
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
622
    "x = np.array([1,2,3],dtype=complex)\n",
623
    "print(x)   ## [ 1.+0.j  2.+0.j  3.+0.j ]"
624 625 626 627 628 629 630 631 632 633
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
634 635 636 637 638 639
    "### Arrays over specified ranges\n",
    "Function | Description\n",
    ":--- | :---\n",
    "`linspace(lo,hi,npts)` | Builds a 1D array with a `npts` entries between `lo` and `hi`\n",
    "`arange(lo,hi,spacing)` | Builds a 1D array spaced with `spacing` starting at `lo` and ending near `hi`\n",
    "`logspace(lo,hi,npts)` | Builds a 1D array with `npts` points between $10^\\mathrm{lo}$ and $10^\\mathrm{hi}$\n",
640 641 642 643 644
    "[`meshgrid(x,y,...)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html#numpy.meshgrid) | Given vectors specifying the range of each axis, builds a grid."
   ]
  },
  {
   "cell_type": "markdown",
645 646 647 648 649
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
650
   "source": [
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    "### Other Constructors\n",
    "\n",
    "Command | Description\n",
    ":--- | :---\n",
    "`empty(shape)` | Build an empty array.\n",
    "`empty_like(a)` | Build an empty array shaped like `a`\n",
    "`eye(N)` | Build a 2D identity matrix with `N` rows and columns\n",
    "`ones(shape)` | build an array of ones with the specified `shape`\n",
    "`ones_like(a)` | Build an array of ones shaped like `a`\n",
    "`zeros(shape)` | build an array of zeros with the specified `shape`\n",
    "`zeros_like(a)` | Build an array of zeros shaped like `a`\n",
    "`full(shape,val)` | Build an array of the specified shape filled with `val`\n",
    "`full_like(a,val)` | Build an array shaped like `a` filled with `val`\n",
    "`random.random(shape)` | Build an array of random numbers with the specified shape\n",
    "\n",
666 667 668 669 670 671 672
    "Examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
673 674 675
    "slideshow": {
     "slide_type": "fragment"
    }
676 677 678
   },
   "outputs": [],
   "source": [
679 680 681 682
    "x = np.ones( [1,3] )      # 3-element row vector\n",
    "y = np.empty_like( x )    # empty 3-element row vector\n",
    "z = np.zeros( [3,3] )     # 3x3 matrix\n",
    "p = np.full_like(z,np.pi) # 3x3 matrix full of 𝜋\n",
683
    "r = np.random.random([2,3])"
684 685 686 687
   ]
  },
  {
   "cell_type": "markdown",
688 689
   "metadata": {
    "slideshow": {
690
     "slide_type": "fragment"
691 692
    }
   },
693
   "source": [
694 695 696 697 698 699 700 701 702 703 704 705
    "All of these can have an additional `dypte` argument to specify the type of array to build (see [above](#Data-Types))."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
James Sutherland's avatar
James Sutherland committed
706
    "\n",
707 708 709 710 711
    "For more information on many other ways of building arrays, see the [numpy docs](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html)"
   ]
  },
  {
   "cell_type": "markdown",
712 713 714 715 716
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
717 718 719 720 721 722
   "source": [
    "## Numpy Matrices\n",
    "\n",
    "Most of the functions mentioned [above](#Other-Constructors) such as `zeros`, `ones`, `full`, `eye`, etc. will create matrices as well - just give the appropriate shape.\n",
    "\n",
    "Additionally, the [diag](https://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html#numpy.diag) function is very useful: \n",
723 724 725 726 727 728 729
    "  * `diag(v,k)` builds a matrix with `v` on its `k`<sup>th</sup> diagonal.  For example, the following builds a tridiagonal matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
730 731 732
    "slideshow": {
     "slide_type": "subslide"
    }
733 734 735 736 737 738 739 740 741 742 743
   },
   "outputs": [],
   "source": [
    "n   = 5\n",
    "d   = np.full(n,-3)\n",
    "ud  = np.full(n-1,1)\n",
    "mat = np.diag(d,0) + np.diag(ud,1) + np.diag(ud,-1)"
   ]
  },
  {
   "cell_type": "markdown",
744 745 746 747 748
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
749 750 751 752 753 754 755 756 757
   "source": [
    "* `diag(m,k)` extracts the `k`<sup>th</sup> diagonal of the matrix `m`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "slideshow": {
758
     "slide_type": "subslide"
759 760 761 762 763 764 765
    }
   },
   "outputs": [],
   "source": [
    "m  = np.random.random([5,5])\n",
    "# extract the main diagonal of m\n",
    "md = np.diag(m,0) "
766 767 768 769
   ]
  },
  {
   "cell_type": "markdown",
770 771 772 773 774
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
775 776 777 778 779 780 781 782 783 784 785 786
   "source": [
    "## Manipulating Numpy Arrays\n",
    "There are many [array manipulation tools](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html#array-manipulation-routines).  Some of the more frequently used ones include:\n",
    "\n",
    "Function | Description\n",
    ":--- | :---\n",
    "[`reshape(a,shape)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape) | Reshape the data in `a` to a `shape`\n",
    "[`ndarray.flat`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flat) | Obtain an iterator over the array\n",
    "[`transpose(a)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html#numpy.transpose) | Transposes the array\n",
    "[`tile(a,nrep)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html#numpy.tile) | Tile `a` `nrep` times.  `nrep` can be an array.\n",
    "[`flip(a,axis)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html#numpy.flip) | Reverse the elements along the `axis` dimension of `a`.\n",
    "[`fliplr(a)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.fliplr.html#numpy.fliplr) | Flip the array in the left/right direction\n",
787 788 789 790 791
    "[`flipud(a)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.flipud.html#numpy.flipud) | Flip the array in the up/down direction."
   ]
  },
  {
   "cell_type": "markdown",
792 793 794 795 796
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
797
   "source": [
798
    "### Indexing and Slicing\n",
799 800 801 802 803 804
    "Numpy arrays are [indexed](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) just like python lists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
805 806 807 808 809
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
810 811 812 813 814 815
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0\n",
James Sutherland's avatar
James Sutherland committed
816 817
      "0.4444444444444444\n",
      "0.8888888888888888\n",
818
      "-2.0\n",
James Sutherland's avatar
James Sutherland committed
819 820 821 822 823
      "1.7777777777777777\n",
      "2.2222222222222223\n",
      "2.6666666666666665\n",
      "3.1111111111111107\n",
      "3.5555555555555554\n",
824 825 826 827 828
      "4.0\n"
     ]
    }
   ],
   "source": [
829 830 831
    "a = np.linspace(0,4,10)\n",
    "a[3] = -2\n",
    "for i in a:\n",
832 833 834 835 836
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
837 838 839 840 841
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
842 843 844 845 846 847 848
   "source": [
    "You can also slice arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
849 850 851 852 853
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
854 855 856 857 858
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
James Sutherland's avatar
James Sutherland committed
859 860 861 862
      "[[0.03533361 0.13114037 0.42474318 0.62253432]\n",
      " [0.75652141 0.64262473 0.42286252 0.67319462]\n",
      " [0.30819661 0.56497425 0.8179415  0.47857807]\n",
      " [0.21509378 0.27477645 0.37631399 0.66887225]]\n",
863 864 865 866 867
      "[1 3 5]\n"
     ]
    }
   ],
   "source": [
868 869 870 871 872
    "a = np.random.random([4,4])\n",
    "print(a)\n",
    "a[1:2,1:3]\n",
    "\n",
    "x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n",
873 874 875 876 877
    "print(x[1:7:2])"
   ]
  },
  {
   "cell_type": "markdown",
878 879 880 881 882
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
883 884 885 886 887 888 889
   "source": [
    "And slice from the \"back\" of arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
890 891 892 893 894
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
895 896 897 898 899 900 901 902 903 904
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[7 6 5]\n"
     ]
    }
   ],
   "source": [
905
    "a = np.arange(0,10,1)\n",
906
    "print(a[-3:4:-1])   # start at third-to last, end at fifth"
907 908 909 910
   ]
  },
  {
   "cell_type": "markdown",
911 912 913 914 915
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
916 917 918 919 920 921 922
   "source": [
    "And slice all after:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
923 924
   "metadata": {
    "slideshow": {
925
     "slide_type": "fragment"
926 927
    }
   },
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 6 7 8 9]\n"
     ]
    }
   ],
   "source": [
    "a = np.arange(0,10,1)\n",
    "print(a[5:])"
   ]
  },
  {
   "cell_type": "markdown",
944 945 946 947 948
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
949 950 951 952 953
   "source": [
    "# Mathematical Operations on Numpy Arrays\n",
    "\n",
    "Numpy arrays support typical mathematical operations like `+`, `-`, `*` (element-wise multipy), `/` (element-wise divide) and `**` (element-wise exponentiation) provided the arrays are the same shape.\n",
    "\n",
954 955 956 957 958 959 960
    "Numpy provides numerous [mathematical functions](https://docs.scipy.org/doc/numpy/reference/routines.math.html) that operate on arrays.  For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
961 962 963
    "slideshow": {
     "slide_type": "fragment"
    }
964 965 966
   },
   "outputs": [],
   "source": [
967 968
    "x = np.linspace(-np.pi,np.pi)\n",
    "y = np.sin(x)\n",
969 970 971 972 973
    "z = x**2"
   ]
  },
  {
   "cell_type": "markdown",
974 975 976 977 978
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
979 980 981 982 983 984 985
   "source": [
    "Or"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
986 987 988 989 990
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
   "outputs": [
    {
     "data": {
      "text/plain": [
       "362880"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
1004
    "n = 10\n",
1005 1006 1007
    "np.prod( np.arange(1,n,1) )  # the factorial of n"
   ]
  },
1008 1009
  {
   "cell_type": "markdown",
1010 1011 1012 1013 1014
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
   "source": [
    "## Array Multiplication\n",
    "\n",
    "Given the arrays \n",
    "$A = \\left[\\begin{array}{cc}\n",
    "1 & 2\\\\\n",
    "3 & 4\n",
    "\\end{array}\\right]$,\n",
    "$b=\\left(\\begin{array}{c} 5\\\\6\\end{array}\\right)$,\n",
    "and\n",
    "$c=\\left(\\begin{array}{c} 7\\\\8\\end{array}\\right)$,"
   ]
  },
  {
   "cell_type": "code",
1030 1031 1032 1033 1034 1035
   "execution_count": 24,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
1036 1037 1038 1039 1040 1041 1042 1043 1044
   "outputs": [],
   "source": [
    "A = np.array([[1,2],[3,4]])\n",
    "b = np.array([[5],[6]])\n",
    "c = np.array([[7],[8]])"
   ]
  },
  {
   "cell_type": "markdown",
1045 1046 1047 1048 1049
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
   "source": [
    "### Elemental Multiplication\n",
    "For those coming from Matlab, the most familiar application of elemental multiplication is on arrays of the same shape.\n",
    "However, elemental multiplication does not require arrays to have the same shape.  For example:\n",
    "\n",
    "Operation | Description | Result \n",
    ":-------- | :---------- | :----- \n",
    "`A * A`   | Square elements in `A` | $\\begin{array}{cc} 1&4\\\\9&16\\end{array}$ \n",
    "`b * c`   | Element-wise multiplication of `b` and `c` | $\\begin{array}{c} 35\\\\48\\end{array}$\n",
    "`A * b`   | Multiply a 2x2 by a 2x1.  Results in a 2x2 | $\\begin{array}{cc} 5&10\\\\18&24\\end{array}$\n",
    "`b.transpose() * c` | Element-Multiply a row vector to a column vector | $\\begin{array}{cc} 35&42\\\\40&48\\end{array}$\n"
   ]
  },
  {
   "cell_type": "markdown",
1065 1066 1067 1068 1069
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
1070 1071
   "source": [
    "### Matrix Multiplication\n",
1072 1073
    "While `*` implies elemental multiplication, `@` implies matrix multiplication.\n",
    "\n",
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    "Here are some example operations on the above arrays:\n",
    "\n",
    "Operation | Result\n",
    ":--- | :---\n",
    "`A @ b` | $\\begin{array}{c} 17 \\\\ 39 \\end{array}$\n",
    "`b.transpose() @ c` | 39\n",
    "`b@c` | error\n",
    "`b.transpose() @ A @ c` | 433"
   ]
  },
1084 1085 1086 1087 1088 1089 1090 1091 1092
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## More useful stuff\n",
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    "Among the other things that you should be aware of:\n",
    "  * Fourier Transform through the [`numpy.fft`](https://docs.scipy.org/doc/numpy/reference/routines.fft.html) module.\n",
    "  * Linear algebra through the [`numpy.linalg`](https://docs.scipy.org/doc/numpy/reference/routines.linalg.html) module.  This includes things like dot products, matrix products, norms, matrix decomositions, etc.\n",
    "  * [Statistics](https://docs.scipy.org/doc/numpy/reference/routines.statistics.html).\n",
    "  * [I/O](https://docs.scipy.org/doc/numpy/reference/routines.io.html) to help with reading/writing arrays from/to disk.\n",
    "  * Advanced [indexing tools](https://docs.scipy.org/doc/numpy/reference/routines.indexing.html)."
   ]
  },
  {
   "cell_type": "markdown",
1103 1104 1105 1106 1107
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
1108 1109 1110 1111 1112 1113 1114 1115
   "source": [
    "\n",
    "# Masking Numpy Arrays\n",
    "To do...  See docs [here](https://docs.scipy.org/doc/numpy/reference/maskedarray.html)"
   ]
  }
 ],
 "metadata": {
1116
  "celltoolbar": "Slideshow",
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
James Sutherland's avatar
James Sutherland committed
1133
   "version": "3.7.0"
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "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
  },
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "navigate_num": "#000000",
    "navigate_text": "#333333",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700",
    "sidebar_border": "#EEEEEE",
    "wrapper_background": "#FFFFFF"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "372px",
    "width": "252px"
   },
   "navigate_menu": true,
   "number_sections": true,
James Sutherland's avatar
James Sutherland committed
1169
   "sideBar": true,
1170
   "threshold": 4,
James Sutherland's avatar
James Sutherland committed
1171
   "toc_cell": true,
1172
   "toc_position": {
James Sutherland's avatar
James Sutherland committed
1173 1174
    "height": "860px",
    "left": "0px",
1175
    "right": "20px",
James Sutherland's avatar
James Sutherland committed
1176 1177
    "top": "158px",
    "width": "214px"
1178
   },
1179
   "toc_section_display": "block",
James Sutherland's avatar
James Sutherland committed
1180
   "toc_window_display": true,
1181 1182
   "widenNotebook": false
  },
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  "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
  },
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 1,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}