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