{ "metadata": { "name": "", "signature": "sha256:b7a6c1ffcdae0ca71f3dcaad68716e764ed17a2664e0e240deac32bd87d7d7df" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "# - compatibility with Python 3\n", "from __future__ import print_function # print('me') instead of print 'me'\n", "from __future__ import division # 1/2 == 0.5, not 0" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "# - show figures inside the notebook\n", "%matplotlib inline" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "# - import common modules\n", "import numpy as np # the Python array package\n", "import matplotlib.pyplot as plt # the Python plotting package" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reshaping with `np.newaxis`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We often want to reshape, adding a single axis length 1. For example, let's say we had a 1d array:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr_1d = np.array([3, 2, 5])\n", "arr_1d" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "array([3, 2, 5])" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We may want to make this into a 2D column vector array, with shape `(3, 1)`. Obviously we could do that with `reshape`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "col_vector = arr_1d.reshape(3, 1)\n", "col_vector" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "array([[3],\n", " [2],\n", " [5]])" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This need, of adding a single length 1 dimension, is so common, that numpy has a fancy way of doing that. To do this, you use the constant `np.newaxis` inside a slicing operation, to return the requested slice, but with an extra length 1 axis in the position you specified:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr_1d[:, np.newaxis] # Add length 1 axis to end, make column vector" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "array([[3],\n", " [2],\n", " [5]])" ] } ], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "arr_1d[np.newaxis, :] # Add length 1 axis to start, make row vector" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 7, "text": [ "array([[3, 2, 5]])" ] } ], "prompt_number": 7 } ], "metadata": {} } ] }