Arrays in Python.ipynb 28 KB
Newer Older
1 2 3 4
{
 "cells": [
  {
   "cell_type": "markdown",
5 6 7 8 9
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
10
   "source": [
11
    "![](Chem-Engingeering_combined-hrz.jpg)\n",
12
    "\n",
13 14 15 16 17 18
    "----\n",
    "# Arrays in Python\n",
    "\n",
    "Contributors:\n",
    " * [James C. Sutherland](sutherland.che.utah.edu)\n",
    "\n",
19 20 21 22 23
    "----\n",
    "\n",
    "__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)"
24 25 26 27
   ]
  },
  {
   "cell_type": "markdown",
28 29 30 31 32
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
33 34 35 36 37
   "source": [
    "## Overview\n",
    "In python, there are a few ways to manage collections of information:\n",
    "  * A [`list`](#Lists) is built-in to the language, and can contain any tipe\n",
    "  * A [`tuple`](#Tuples) is also built-in to the language, and is similar to a list, but is immutable.\n",
38
    "  * 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."
39 40 41 42
   ]
  },
  {
   "cell_type": "markdown",
43 44 45 46 47
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
48 49
   "source": [
    "# Lists\n",
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    "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": [
69 70 71 72 73 74 75 76 77 78 79 80
    "# 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",
81
    "print(my_list[2])        # 5"
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   ]
  },
  {
   "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",
97 98 99 100 101 102 103 104
   "metadata": {},
   "source": [
    "___Caution___: copying arrays in python is unique:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
105
   "metadata": {
106
    "collapsed": true
107
   },
108
   "outputs": [],
109
   "source": [
110
    "a = [1,2,3]\n",
111
    "b = a"
112 113 114 115
   ]
  },
  {
   "cell_type": "markdown",
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
   "metadata": {},
   "source": [
    "makes `b` alias to `a`.  This means that"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "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,
166 167
   "metadata": {
    "slideshow": {
168
     "slide_type": "subslide"
169 170
    }
   },
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
   "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": {},
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
   "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",
206
    "`index(entry)` | return the index at which the first occurence of `entry` occurs | `my_list.index(x)`"
207 208 209 210
   ]
  },
  {
   "cell_type": "markdown",
211 212 213 214 215 216 217 218
   "metadata": {},
   "source": [
    "You can also use the keyword `in` with a list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
219 220 221 222 223
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
   "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": {},
244 245 246
   "source": [
    "## Indexing and Slicing Lists\n",
    "\n",
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    "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,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "fruits = ['apple','banana','grapefruit','orange']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
265 266 267 268 269 270 271 272 273 274
    "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",
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    "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": [
303 304 305 306
    "x = [1,2,3,4]\n",
    "y = x[1:3]\n",
    "y.reverse()\n",
    "x[0:2] = y\n",
307
    "print(x)"
308 309 310 311
   ]
  },
  {
   "cell_type": "markdown",
312 313 314 315 316
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
317 318
   "source": [
    "## Loops and Lists\n",
319 320 321 322 323
    "There are a few ways to loop over lists.  This is perhaps best illustrated by a few examples."
   ]
  },
  {
   "cell_type": "markdown",
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
   "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"
     ]
342
    }
343
   ],
344
   "source": [
345 346
    "fruits = ['apple','banana','orange']\n",
    "for i in fruits:\n",
347
    "    print(i)"
348 349 350 351 352 353 354 355 356
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
357 358 359 360 361 362 363
   "source": [
    "Here, `i` is an _iterator_ that represents each entry in the list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
364
   "source": [
365
    "### Index loops\n",
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    "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": [
385 386
    "fruits = ['apple','banana','orange']\n",
    "for i in range(0,len(fruits)):\n",
387
    "    print('Fruit {} = {}'.format(i,fruits[i]))"
388 389 390 391 392 393 394 395 396
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
397 398 399 400 401 402 403
   "source": [
    "Note that `range(lo,hi)` creates a range of integers from __`lo`__ to __`hi-1`__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
404
   "source": [
405 406 407
    "### 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",
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    "we can do this by:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9]\n"
     ]
    }
   ],
   "source": [
425
    "x = [i**2 for i in range(1,4)]\n",
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    "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": [
462
    "List comprehensions provide a relatively simple syntax to build these types of lists."
463 464 465 466
   ]
  },
  {
   "cell_type": "markdown",
467 468 469 470 471
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
472 473 474 475 476 477 478 479 480 481 482 483 484
   "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",
485
   "metadata": {},
486 487 488 489 490 491 492 493
   "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",
494 495 496 497 498 499 500 501 502 503 504 505
    "Here and below, we will assume that you have:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
506 507 508 509
   ]
  },
  {
   "cell_type": "markdown",
510 511 512 513 514
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
515 516 517 518 519 520 521
   "source": [
    "so that we can use __`np.`__ to shorten reference to numpy functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
522 523
   "source": [
    "## Constructing Numpy Arrays\n",
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    "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": [
547 548 549
    "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",
550
    "print(y.shape,y)"
551 552 553 554 555 556 557 558 559 560 561
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Data Types\n",
562 563 564 565 566 567 568 569 570
    "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",
571 572 573
    "(other) | User-defined data types"
   ]
  },
574 575 576 577 578 579 580
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Example"
   ]
  },
581 582 583 584 585 586 587 588
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
589
    "x = np.array([1,2,3],dtype=complex)\n",
590
    "print(x)   ## [ 1.+0.j  2.+0.j  3.+0.j ]"
591 592 593 594 595 596 597 598 599 600
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
601 602 603 604 605 606
    "### 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",
607 608 609 610 611
    "[`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",
612
   "metadata": {},
613
   "source": [
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
    "### 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",
629 630 631 632 633 634 635 636 637 638 639
    "Examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
640 641 642 643
    "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",
644
    "r = np.random.random([2,3])"
645 646 647 648
   ]
  },
  {
   "cell_type": "markdown",
649 650
   "metadata": {
    "slideshow": {
651
     "slide_type": "subslide"
652 653
    }
   },
654 655 656 657 658 659 660 661 662
   "source": [
    "All of these can have an additional `dypte` argument to specify the type of array to build (see [above](#Data-Types)).\n",
    "\n",
    "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",
   "metadata": {},
663 664 665 666 667 668
   "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",
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    "  * `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": {
    "collapsed": true
   },
   "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",
   "metadata": {},
   "source": [
    "* `diag(m,k)` extracts the `k`<sup>th</sup> diagonal of the matrix `m`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
697
    "collapsed": true,
698 699 700 701 702 703 704 705 706
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "m  = np.random.random([5,5])\n",
    "# extract the main diagonal of m\n",
    "md = np.diag(m,0) "
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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",
724 725 726 727 728
    "[`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",
729
   "metadata": {},
730
   "source": [
731
    "### Indexing and Slicing\n",
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    "Numpy arrays are [indexed](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) just like python lists:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0\n",
      "0.444444444444\n",
      "0.888888888889\n",
      "-2.0\n",
      "1.77777777778\n",
      "2.22222222222\n",
      "2.66666666667\n",
      "3.11111111111\n",
      "3.55555555556\n",
      "4.0\n"
     ]
    }
   ],
   "source": [
758 759 760
    "a = np.linspace(0,4,10)\n",
    "a[3] = -2\n",
    "for i in a:\n",
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also slice arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
780 781 782 783
      "[[ 0.51507018  0.4513881   0.88552337  0.40618144]\n",
      " [ 0.90818009  0.49131706  0.47977753  0.88744529]\n",
      " [ 0.6993323   0.37416041  0.17007291  0.6198272 ]\n",
      " [ 0.57498962  0.79422007  0.2323055   0.6382159 ]]\n",
784 785 786 787 788
      "[1 3 5]\n"
     ]
    }
   ],
   "source": [
789 790 791 792 793
    "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",
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    "print(x[1:7:2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And slice from the \"back\" of arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[7 6 5]\n"
     ]
    }
   ],
   "source": [
818
    "a = np.arange(0,10,1)\n",
819
    "print(a[-3:4:-1])   # start at third-to last, end at fifth"
820 821 822 823
   ]
  },
  {
   "cell_type": "markdown",
824 825 826 827 828 829 830 831
   "metadata": {},
   "source": [
    "And slice all after:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
832 833
   "metadata": {
    "slideshow": {
834
     "slide_type": "subslide"
835 836
    }
   },
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
   "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",
   "metadata": {},
854 855 856 857 858
   "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",
859 860 861 862 863 864 865 866 867 868 869
    "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": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
870 871
    "x = np.linspace(-np.pi,np.pi)\n",
    "y = np.sin(x)\n",
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
    "z = x**2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "362880"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
899
    "n = 10\n",
900 901 902
    "np.prod( np.arange(1,n,1) )  # the factorial of n"
   ]
  },
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
  {
   "cell_type": "markdown",
   "metadata": {},
   "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",
   "execution_count": 66,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = np.array([[1,2],[3,4]])\n",
    "b = np.array([[5],[6]])\n",
    "c = np.array([[7],[8]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Consider the following operations:\n",
    "\n",
    "Operation | Description\n",
    ":--- | :--- | :---\n",
    "`*` | Elemental multiplication\n",
    "`@` | Matrix multiplication"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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",
   "metadata": {},
   "source": [
    "### Matrix Multiplication\n",
    "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"
   ]
  },
973 974 975 976 977 978 979 980 981
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## More useful stuff\n",
982 983 984 985 986 987 988 989 990 991
    "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",
992 993 994 995 996
   "metadata": {
    "slideshow": {
     "slide_type": "skip"
    }
   },
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
   "source": [
    "\n",
    "# Masking Numpy Arrays\n",
    "To do...  See docs [here](https://docs.scipy.org/doc/numpy/reference/maskedarray.html)"
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
1021
   "version": "3.6.2"
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  },
  "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,
   "sideBar": false,
   "threshold": 4,
   "toc_cell": false,
   "toc_position": {
1061
    "height": "532px",
1062 1063 1064
    "left": "1px",
    "right": "20px",
    "top": "106px",
1065
    "width": "287px"
1066 1067
   },
   "toc_section_display": "none",
1068
   "toc_window_display": false,
1069 1070
   "widenNotebook": false
  },
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
  "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
  },
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 1,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}