Arrays in Python.ipynb 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "# Arrays in Python\n",
    "\n",
    "Contributors:\n",
    " * [James C. Sutherland](sutherland.che.utah.edu)\n",
    "\n",
    "----"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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",
    "  * 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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Lists\n",
    "A _list_ in python is enclosed by square brackets, and can contain any types (including other lists):\n",
    "```\n",
    "# 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",
    "print(my_list[2])        # 5\n",
    "```\n",
    "\n",
    "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.\n",
    "\n",
    "___Caution___: copying arrays in python is unique:\n",
    "```\n",
    "a = [1,2,3]\n",
    "b = a\n",
    "```\n",
    "makes `b` alias to `a`.  This means that\n",
    "```\n",
    "b[1]=5\n",
    "```\n",
    "also changes `a[1]` to 5.\n",
    "To make a full copy of an array, use the `copy` method:\n",
    "```\n",
    "b = a         # b and a are the same array\n",
    "c = a.copy()  # c and a are different arrays with the same contents\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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",
    "`index(entry)` | return the index at which the first occurence of `entry` occurs | `my_list.index(x)`\n",
    "\n",
    "You can also use the keyword `in` with a list:\n",
    "```\n",
    "if 'banana' in fruits:\n",
    "    print('Yes!')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Indexing and Slicing Lists\n",
    "\n",
    "Indexing a list is done with the `[]` operator, and is 0-based (0 indicates the first entry in the list).  For example, given:\n",
    "```\n",
    "fruits = ['apple','banana','grapefruit','orange']\n",
    "```\n",
    "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",
    "The `:` operator allows us to perform _slicing_, accessing a subset of the entries in a list.\n",
    "\n",
    "You can also use slicing to replace elements of a list.  For example:\n",
    "```\n",
    "x = [1,2,3,4]\n",
    "y = x[1:3]\n",
    "y.reverse()\n",
    "x[0:2] = y\n",
    "print(x)\n",
    "```\n",
    "produces:\n",
    "```\n",
    "[3, 2, 3, 4]\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loops and Lists\n",
    "There are a few ways to loop over lists.  This is perhaps best illustrated by a few examples.\n",
    "\n",
    "### Iterating a list\n",
    "```\n",
    "fruits = ['apple','banana','orange']\n",
    "for i in fruits:\n",
    "    print(i)\n",
    "```\n",
    "Here, `i` is an _iterator_ that represents each entry in the list\n",
    "\n",
    "### Index loops\n",
    "Here we use the `range()` function, which builds a range space for the loop. This allows us to use `i` as an index:\n",
    "```\n",
    "fruits = ['apple','banana','orange']\n",
    "for i in range(0,len(fruits)):\n",
    "    print('Fruit #',i,'=', fruits[i])\n",
    "```\n",
    "Note that `range(lo,hi)` creates a range of integers from __`lo`__ to __`hi-1`__\n",
    "### 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",
    "we can do this by:\n",
    "```\n",
    "x = [i**2 for i in range(1,4)]\n",
    "```\n",
    "Similarly, to achieve $x_i=2^i, \\; i=1\\ldots 8$, we can do:\n",
    "```\n",
    "x = [2**i for i in range(1,9)]\n",
    "```\n",
    "List comprehensions provide a relatively simple syntax to build these types of lists.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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",
   "metadata": {},
   "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",
    "Here and below, we will assume that you have:\n",
    "```\n",
    "import numpy as np\n",
    "```\n",
    "so that we can use __`np.`__ to shorten reference to numpy functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Constructing Numpy Arrays\n",
    "A numpy array is characterized by its _shape_ and the type of elements it contains.\n",
    "```\n",
    "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",
    "print(y.shape,y)\n",
    "```\n",
    "\n",
    "#### Data Types\n",
    "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",
    "(other) | User-defined data types\n",
    "\n",
    "#### Example\n",
    "```\n",
    "x = np.array([1,2,3],dtype=complex)\n",
    "print(x)   ## [ 1.+0.j  2.+0.j  3.+0.j ]\n",
    "```\n",
    "\n",
    "### 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",
    "[`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.\n",
    "\n",
    "\n",
    "### 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",
    "Examples:\n",
    "```\n",
    "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",
    "r = np.random.random([2,3])\n",
    "```\n",
    "\n",
    "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": {},
   "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",
    "  * `diag(v,k)` builds a matrix with `v` on its `k`<sup>th</sup> diagonal.  For example, the following builds a tridiagonal matrix:\n",
    "  ```\n",
    "  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)\n",
    "  ```\n",
    "  * `diag(m,k)` extracts the `k`<sup>th</sup> diagonal of the matrix `m`\n",
    "  ```\n",
    "  m  = np.random.random([5,5])\n",
    "  md = np.diag(m,0)) # main diagonal of m\n",
    "  ```\n"
   ]
  },
  {
   "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",
    "[`flipud(a)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.flipud.html#numpy.flipud) | Flip the array in the up/down direction.\n",
    "\n",
    "### Indexing and Slicing\n",
    "Numpy arrays are [indexed](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html) just like python lists:\n",
    "```\n",
    "a = np.linspace(0,4,10)\n",
    "a[3] = -2\n",
    "for i in a:\n",
    "    print(i)\n",
    "```\n",
    "\n",
    "You can also slice arrays:\n",
    "```\n",
    "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",
    "print(x[1:7:2])\n",
    "```\n",
    "And slice from the \"back\" of arrays:\n",
    "```\n",
    "a = np.arange(0,10,1)\n",
    "print(a[-3:4:-1])   # start at third-to last, end at fifth\n",
    "``` \n",
    "And slice all after:\n",
    "```\n",
    "a = np.arange(0,10,1)\n",
    "print(a[5:])\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# 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",
    "Numpy provides numerous [mathematical functions](https://docs.scipy.org/doc/numpy/reference/routines.math.html) that operate on arrays.  For example:\n",
    "```\n",
    "x = np.linspace(-np.pi,np.pi)\n",
    "y = np.sin(x)\n",
    "z = x**2\n",
    "```\n",
    "Or\n",
    "```\n",
    "n = 10\n",
    "np.prod( np.arange(1,n,1) )  # the factorial of n\n",
    "```\n",
    "\n",
    "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",
   "metadata": {},
   "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",
   "version": "3.6.1"
  },
  "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": {
    "height": "220px",
    "left": "1px",
    "right": "20px",
    "top": "106px",
    "width": "202px"
   },
   "toc_section_display": "none",
   "toc_window_display": true,
   "widenNotebook": false
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 1,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}