100% found this document useful (2 votes)
92 views

Full Learning IPython For Interactive Computing and Data Visualization - Second Edition Cyrille Rossant Ebook All Chapters

IPython

Uploaded by

capungagario
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
92 views

Full Learning IPython For Interactive Computing and Data Visualization - Second Edition Cyrille Rossant Ebook All Chapters

IPython

Uploaded by

capungagario
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Download the full version of the textbook now at textbookfull.

com

Learning IPython for Interactive Computing


and Data Visualization - Second Edition
Cyrille Rossant

https://textbookfull.com/product/learning-ipython-
for-interactive-computing-and-data-visualization-
second-edition-cyrille-rossant/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Interactive Data Visualization for the Web Murray

https://textbookfull.com/product/interactive-data-visualization-for-
the-web-murray/

textbookfull.com

Interactive Data Visualization for the Web An Introduction


to Designing with D3 1st Edition Murray

https://textbookfull.com/product/interactive-data-visualization-for-
the-web-an-introduction-to-designing-with-d3-1st-edition-murray/

textbookfull.com

Python for Data Analysis Data Wrangling with Pandas NumPy


and IPython Wes Mckinney

https://textbookfull.com/product/python-for-data-analysis-data-
wrangling-with-pandas-numpy-and-ipython-wes-mckinney/

textbookfull.com

Lectures on light : nonlinear and quantum optics using the


density matrix 2nd Edition Rand

https://textbookfull.com/product/lectures-on-light-nonlinear-and-
quantum-optics-using-the-density-matrix-2nd-edition-rand/

textbookfull.com
Love Canal : a toxic history from Colonial times to the
present 1st Edition Newman

https://textbookfull.com/product/love-canal-a-toxic-history-from-
colonial-times-to-the-present-1st-edition-newman/

textbookfull.com

The Routledge Handbook of Mass Media Ethics 2nd Edition


Lee Wilkins

https://textbookfull.com/product/the-routledge-handbook-of-mass-media-
ethics-2nd-edition-lee-wilkins/

textbookfull.com

Geothermics Heat Flow in the Lithosphere 2nd Edition


Vincenzo Pasquale

https://textbookfull.com/product/geothermics-heat-flow-in-the-
lithosphere-2nd-edition-vincenzo-pasquale/

textbookfull.com

Building physics heat air and moisture fundamentals and


engineering methods with examples and exercises Third
Edition Hens
https://textbookfull.com/product/building-physics-heat-air-and-
moisture-fundamentals-and-engineering-methods-with-examples-and-
exercises-third-edition-hens/
textbookfull.com

Quantitative Evaluation of Systems 16th International


Conference QEST 2019 Glasgow UK September 10 12 2019
Proceedings David Parker
https://textbookfull.com/product/quantitative-evaluation-of-
systems-16th-international-conference-qest-2019-glasgow-uk-
september-10-12-2019-proceedings-david-parker/
textbookfull.com
Distributed Computer and Communication Networks 17th
International Conference DCCN 2013 Moscow Russia October 7
10 2013 Revised Selected Papers 1st Edition Vladimir
Vishnevsky
https://textbookfull.com/product/distributed-computer-and-
communication-networks-17th-international-conference-dccn-2013-moscow-
russia-october-7-10-2013-revised-selected-papers-1st-edition-vladimir-
vishnevsky/
textbookfull.com
[1]
Learning IPython for Interactive
Computing and Data
Visualization
Second Edition

Get started with Python for data analysis and numerical


computing in the Jupyter notebook

Cyrille Rossant

BIRMINGHAM - MUMBAI
Learning IPython for Interactive Computing
and Data Visualization
Second Edition

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book
is sold without warranty, either express or implied. Neither the author nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: April 2013

Second edition: October 2015

Production reference: 1151015

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78398-698-9

www.packtpub.com
Credits

Author Project Coordinator


Cyrille Rossant Shweta H Birwatkar

Reviewers Proofreader
Damián Avila Safis Editing
Nicola Rainiero
G Scott Stukey Indexer
Monica Ajmera Mehta

Commissioning Editor
Kartikey Pandey Production Coordinator
Conidon Miranda

Acquisition Editors
Kartikey Pandey Cover Work
Conidon Miranda
Richard Brookes-Bland

Content Development Editor


Arun Nadar

Technical Editor
Pranil Pathare

Copy Editor
Stephen Copestake
About the Author

Cyrille Rossant is a researcher in neuroinformatics, and is a graduate of Ecole


Normale Superieure, Paris, where he studied mathematics and computer science.
He has worked at Princeton University, University College London, and College
de France. As part of his data science and software engineering projects, he gained
experience in machine learning, high-performance computing, parallel computing,
and big data visualization.

He is one of the main developers of VisPy, a high-performance visualization package


in Python. He is the author of the IPython Interactive Computing and Visualization
Cookbook, Packt Publishing, an advanced-level guide to data science and numerical
computing with Python, and the sequel of this book.

I am grateful to Nick Fiorentini for his help during the revision of


the book. I would also like to thank my family and notably my wife
Claire for their support.
About the Reviewers

Damián Avila is a software developer and data scientist (formerly a biochemist)


from Córdoba, Argentina.

His main focus of interest is data science, visualization, finance, and


IPython/Jupyter-related projects.

In the open source area, he is a core developer for several interesting and popular
projects, such as IPython/Jupyter, Bokeh, and Nikola. He has also started his own
projects, being RISE, an extension to enable amazing live slides in the Jupyter
notebook, the most popular one. He has also written several tutorials about
the Scientific Python tools (available at Github) and presented several talks
at international conferences.

Currently, he is working at Continuum Analytics.

Nicola Rainiero is a civil geotechnical engineer with a background in the


construction industry as a self-employed designer engineer. He is also specialized
in the renewable energy field and has collaborated with the Sant'Anna University
of Pisa for two European projects, REGEOCITIES and PRISCA, using qualitative
and quantitative data analysis techniques.

He has an ambition to simplify his work with open software and use and develop
new ones; sometimes obtaining good results, at other times, negative. You can reach
Nicola on his website at http://rainnic.altervista.org.

A special thanks to Packt Publishing for this opportunity to


participate in the reviewing of this book. I thank my family,
especially my parents, for their physical and moral support.
www.PacktPub.com

Support files, eBooks, discount offers,


and more
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for
a range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view 9 entirely free books. Simply use your login credentials for immediate access.
Table of Contents
Preface vii
Chapter 1: Getting Started with IPython 1
What are Python, IPython, and Jupyter? 1
Jupyter and IPython 2
What this book covers 4
References 5
Installing Python with Anaconda 5
Downloading Anaconda 6
Installing Anaconda 6
Before you get started... 7
Opening a terminal 7
Finding your home directory 8
Manipulating your system path 8
Testing your installation 9
Managing environments 9
Common conda commands 10
References 11
Downloading the notebooks 12
Introducing the Notebook 13
Launching the IPython console 13
Launching the Jupyter Notebook 14
The Notebook dashboard 15
The Notebook user interface 16
Structure of a notebook cell 16
Markdown cells 17
Code cells 18

[i]
Table of Contents

The Notebook modal interface 19


Keyboard shortcuts available in both modes 19
Keyboard shortcuts available in the edit mode 19
Keyboard shortcuts available in the command mode 20
References 20
A crash course on Python 20
Hello world 21
Variables 21
String escaping 23
Lists 24
Loops 26
Indentation 27
Conditional branches 27
Functions 28
Positional and keyword arguments 29
Passage by assignment 30
Errors 31
Object-oriented programming 32
Functional programming 34
Python 2 and 3 35
Going beyond the basics 36
Ten Jupyter/IPython essentials 37
Using IPython as an extended shell 37
Learning magic commands 42
Mastering tab completion 45
Writing interactive documents in the Notebook with Markdown 47
Creating interactive widgets in the Notebook 49
Running Python scripts from IPython 51
Introspecting Python objects 53
Debugging Python code 54
Benchmarking Python code 55
Profiling Python code 56
Summary 58
Chapter 2: Interactive Data Analysis with pandas 59
Exploring a dataset in the Notebook 59
Provenance of the data 60
Downloading and loading a dataset 61
Making plots with matplotlib 63
Descriptive statistics with pandas and seaborn 67

[ ii ]
Table of Contents

Manipulating data 69
Selecting data 69
Selecting columns 70
Selecting rows 70
Filtering with boolean indexing 72
Computing with numbers 73
Working with text 75
Working with dates and times 76
Handling missing data 77
Complex operations 78
Group-by 78
Joins 80
Summary 83
Chapter 3: Numerical Computing with NumPy 85
A primer to vector computing 85
Multidimensional arrays 86
The ndarray 86
Vector operations on ndarrays 87
How fast are vector computations in NumPy? 88
How an ndarray is stored in memory 89
Why operations on ndarrays are fast 91
Creating and loading arrays 91
Creating arrays 91
Loading arrays from files 93
Basic array manipulations 94
Computing with NumPy arrays 97
Selection and indexing 98
Boolean operations on arrays 99
Mathematical operations on arrays 100
A density map with NumPy 103
Other topics 107
Summary 108
Chapter 4: Interactive Plotting and Graphical Interfaces 109
Choosing a plotting backend 109
Inline plots 109
Exported figures 111
GUI toolkits 111
Dynamic inline plots 113
Web-based visualization 114

[ iii ]
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents

matplotlib and seaborn essentials 115


Common plots with matplotlib 116
Customizing matplotlib figures 120
Interacting with matplotlib figures in the Notebook 122
High-level plotting with seaborn 124
Image processing 126
Further plotting and visualization libraries 129
High-level plotting 129
Bokeh 130
Vincent and Vega 130
Plotly 131
Maps and geometry 132
The matplotlib Basemap toolkit 132
GeoPandas 133
Leaflet wrappers: folium and mplleaflet 134
3D visualization 134
Mayavi 134
VisPy 135
Summary 135
Chapter 5: High-Performance and Parallel Computing 137
Accelerating Python code with Numba 138
Random walk 138
Universal functions 141
Writing C in Python with Cython 143
Installing Cython and a C compiler for Python 143
Implementing the Eratosthenes Sieve in Python and Cython 144
Distributing tasks on several cores with IPython.parallel 148
Direct interface 149
Load-balanced interface 150
Further high-performance computing techniques 153
MPI 153
Distributed computing 153
C/C++ with Python 154
GPU computing 154
PyPy 155
Julia 155
Summary 155

[ iv ]
Table of Contents

Chapter 6: Customizing IPython 157


Creating a custom magic command in an IPython extension 157
Writing a new Jupyter kernel 160
Displaying rich HTML elements in the Notebook 165
Displaying SVG in the Notebook 165
JavaScript and D3 in the Notebook 167
Customizing the Notebook interface with JavaScript 170
Summary 172
Index 173

[v]
Preface
Data analysis skills are now essential in scientific research, engineering, finance,
economics, journalism, and many other domains. With its high accessibility and
vibrant ecosystem, Python is one of the most appreciated open source languages for
data science.

This book is a beginner-friendly introduction to the Python data analysis platform,


focusing on IPython (Interactive Python) and its Notebook. While IPython is an
enhanced interactive Python terminal specifically designed for scientific computing
and data analysis, the Notebook is a graphical interface that combines code, text,
equations, and plots in a unified interactive environment.

The first edition of Learning IPython for Interactive Computing and Data Visualization
was published in April 2013, several months before the release of IPython 1.0. This
new edition targets IPython 4.0, released in August 2015. In addition to reflecting the
novelties of this new version of IPython, the present book is also more accessible to
non-programmer beginners. The first chapter contains a brand new crash course on
Python programming, as well as detailed installation instructions.

Since the first edition of this book, IPython's popularity has grown significantly,
with an estimated user base of several millions of people and ongoing collaborations
with large companies like Microsoft, Google, IBM, and others. The project itself has
been subject to important changes, with a refactoring into a language-independent
interface called the Jupyter Notebook, and a set of backend kernels in various
languages. The Notebook is no longer reserved to Python; it can now also be used
with R, Julia, Ruby, Haskell, and many more languages (50 at the time of this
writing!).

[ vii ]
Preface

The Jupyter project has received significant funding in 2015 from the Leona M. and
Harry B. Helmsley Charitable Trust, the Gordon and Betty Moore Foundation, and
the Alfred P. Sloan Foundation, which will allow the developers to focus on the
growth and maturity of the project in the years to come.

Here are a few references:

• Home page for the Jupyter project at http://jupyter.org/


• Announcement of the funding for Jupyter at https://blog.jupyter.
org/2015/07/07/jupyter-funding-2015/
• Detail of the project's grant at https://blog.jupyter.org/2015/07/07/
project-jupyter-computational-narratives-as-the-engine-of-
collaborative-data-science/

What this book covers


Chapter 1, Getting Started with IPython, is a thorough and beginner-friendly
introduction to Anaconda (a popular Python distribution), the Python language, the
Jupyter Notebook, and IPython.

Chapter 2, Interactive Data Analysis with pandas, is a hands-on introduction to


interactive data analysis and visualization in the Notebook with pandas, matplotlib,
and seaborn.

Chapter 3, Numerical Computing with NumPy, details how to use NumPy for efficient
computing on multidimensional numerical arrays.

Chapter 4, Interactive Plotting and Graphical Interfaces, explores many capabilities of


Python for interactive plotting, graphics, image processing, and interactive graphical
interfaces in the Jupyter Notebook.

Chapter 5, High-Performance and Parallel Computing, introduces the various techniques


you can employ to accelerate your numerical computing code, namely parallel
computing and compilation of Python code.

Chapter 6, Customizing IPython, shows how IPython and the Jupyter Notebook can be
extended for customized use-cases.

[ viii ]
Preface

What you need for this book


The following software is required for the book:

• Anaconda with Python 3


• Windows, Linux, or OS X can be used as a platform

Who this book is for


This book targets anyone who wants to analyze data or perform numerical
simulations of mathematical models.

Since our world is becoming more and more data-driven, knowing how to analyze
data effectively is an essential skill to learn. If you're used to spreadsheet programs
like Microsoft Excel, you will appreciate Python for its much larger range of analysis
and visualization possibilities. Knowing this general-purpose language will also let
you share your data and analysis with other programs and libraries.

In conclusion, this book will be useful to students, scientists, engineers, analysts,


journalists, statisticians, economists, hobbyists, and all data enthusiasts.

Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"Run it with a command like bash Anaconda3-2.3.0-Linux-x86_64.sh (if
necessary, replace the filename by the one you downloaded)."

A block of code is set as follows:


def load_ipython_extension(ipython):
"""This function is called when the extension is loaded.
It accepts an IPython InteractiveShell instance.
We can register the magic with the `register_magic_function`
method of the shell instance."""
ipython.register_magic_function(cpp, 'cell')

[ ix ]
Preface

Any command-line input or output is written as follows:


$ python
Python 3.4.3 |Anaconda 2.3.0 (64-bit)| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

New terms and important words are shown in bold. Words that you see on the
screen, for example, in menus or dialog boxes, appear in the text like this: "To create
a new notebook, click on the New button, and select Notebook (Python 3)."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention


the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.
You can also report any issues at https://github.com/ipython-books/minibook-
2nd-code/issues.

[x]
Preface

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files from your account at http://www.
packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files e-mailed directly to you. You will also find the book's
code on this GitHub repository: https://github.com/ipython-books/minibook-
2nd-code.

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/
diagrams used in this book. The color images will help you better understand the
changes in the output. You can download this file from https://www.packtpub.
com/sites/default/files/downloads/6989OS_ColouredImages.pdf.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

[ xi ]
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated


material.

We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.
Getting Started with IPython
In this chapter, we will cover the following topics:

• What are Python, IPython, and Jupyter?


• Installing Python with Anaconda
• Introducing the Notebook
• A crash course on Python
• Ten Jupyter/IPython essentials

What are Python, IPython, and Jupyter?


Python is an open source general-purpose language created by Guido van Rossum
in the late 1980s. It is widely-used by system administrators and developers for many
purposes: for example, automating routine tasks or creating a web server. Python is
a flexible and powerful language, yet it is sufficiently simple to be taught to school
children with great success.

In the past few years, Python has also emerged as one of the leading open
platforms for data science and high-performance numerical computing. This might
seem surprising as Python was not originally designed for scientific computing.
Python's interpreted nature makes it much slower than lower-level languages like
C or Fortran, which are more amenable to number crunching and the efficient
implementation of complex mathematical algorithms.

However, the performance of these low-level languages comes at a cost: they are
hard to use and they require advanced knowledge of how computers work. In the
late 1990s, several scientists began investigating the possibility of using Python for
numerical computing by interoperating it with mainstream C/Fortran scientific
libraries. This would bring together the ease-of-use of Python with the performance
of C/Fortran: the dream of any scientist!

[1]
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Getting Started with IPython

Consequently, the past 15 years have seen the development of widely-used libraries
such as NumPy (providing a practical array data structure), SciPy (scientific
computing), matplotlib (graphical plotting), pandas (data analysis and statistics),
scikit-learn (machine learning), SymPy (symbolic computing), and Jupyter/IPython
(efficient interfaces for interactive computing). Python, along with this set of
libraries, is sometimes referred to as the SciPy stack or PyData platform.

Competing platforms
Python has several competitors. For example, MATLAB (by Mathworks)
is a commercial software focusing on numerical computing that is
widely-used in scientific research and engineering. SPSS (by IBM) is a
commercial software for statistical analysis. Python, however, is free and
open source, and that's one of its greatest strengths. Alternative open
source platforms include R (specialized in statistics) and Julia (a young
language for high-performance numerical computing).

More recently, this platform has gained popularity in other non-academic


communities such as finance, engineering, statistics, data science, and others.

This book provides a solid introduction to the whole platform by focusing on one
of its main components: Jupyter/IPython.

Jupyter and IPython


IPython was created in 2001 by Fernando Perez (the I in IPython stands for
"interactive"). It was originally meant to be a convenient command-line interface
to the scientific Python platform. In scientific computing, trial and error is the rule
rather than the exception, and this requires an efficient interface that allows for
interactive exploration of algorithms, data, and graphs.

In 2011, IPython introduced the interactive Notebook. Inspired by commercial


software such as Maple (by Maplesoft) or Mathematica (by Wolfram Research), the
Notebook runs in a browser and provides a unified web interface where code, text,
mathematical equations, plots, graphics, and interactive graphical controls can be
combined into a single document. This is an ideal interface for scientific computing.
Here is a screenshot of a notebook:

[2]
Chapter 1

Example of a notebook

It quickly became clear that this interface could be used with languages other than
Python such as R, Julia, Lua, Ruby, and many others. Further, the Notebook is not
restricted to scientific computing: it can be used for academic courses, software
documentation, or book writing thanks to conversion tools targeting Markdown,
HTML, PDF, ODT, and many other formats. Therefore, the IPython developers
decided in 2014 to acknowledge the general-purpose nature of the Notebook by
giving a new name to the project: Jupyter.

Jupyter features a language-independent Notebook platform that can work with


a variety of kernels. Implemented in any language, a kernel is the backend of the
Notebook interface. It manages the interactive session, the variables, the data, and so
on. By contrast, the Notebook interface is the frontend of the system. It manages the
user interface, the text editor, the plots, and so on. IPython is henceforth the name
of the Python kernel for the Jupyter Notebook. Other kernels include IR, IJulia,
ILua, IRuby, and many others (50 at the time of this writing).

[3]
Getting Started with IPython

In August 2015, the IPython/Jupyter developers achieved the "Big Split" by splitting
the previous monolithic IPython codebase into a set of smaller projects, including
the language-independent Jupyter Notebook (see https://blog.jupyter.
org/2015/08/12/first-release-of-jupyter/). For example, the parallel
computing features of IPython are now implemented in a standalone Python
package named ipyparallel, the IPython widgets are implemented in ipywidgets,
and so on. This separation makes the code of the project more modular and facilitates
third-party contributions. IPython itself is now a much smaller project than before
since it only features the interactive Python terminal and the Python kernel for the
Jupyter Notebook.

You will find the list of changes in IPython 4.0 at http://ipython.


readthedocs.org/en/latest/whatsnew/version4.html.
Many internal IPython imports have been deprecated due to the
code reorganization. Warnings are raised if you attempt to perform
a deprecated import. Also, the profiles have been removed and
replaced with a unique default profile. However, you can simulate
this functionality with environment variables. You will find more
information at http://jupyter.readthedocs.org.

What this book covers


This book covers the Jupyter Notebook 1.0 and focuses on its Python kernel,
IPython 4.0. In this chapter, we will introduce the platform, the Python language,
the Jupyter Notebook interface, and IPython. In the remaining chapters, we will
cover data analysis and scientific computing in Jupyter/IPython with the help of
mainstream scientific libraries such as NumPy, pandas, and matplotlib.

This book gives you a solid introduction to Jupyter and the SciPy
platform. The IPython Interactive Computing and Visualization Cookbook
(http://ipython-books.github.io/cookbook/) is the sequel of
this introductory-level book. In 15 chapters and more than 500 pages,
it contains a hundred recipes covering a wide range of interactive
numerical computing techniques and data science topics. The IPython
Cookbook is an excellent addition to the present IPython minibook if
you're interested in delving into the platform in much greater detail.

[4]
Chapter 1

References
Here are a few references about IPython and the Notebook:

• The main Jupyter page at: http://jupyter.org/


• The main Jupyter documentation at: https://jupyter.readthedocs.org/
en/latest/
• The main IPython page at: http://ipython.org/
• Jupyter on GitHub at: https://github.com/jupyter
• Try Jupyter online at: https://try.jupyter.org/
• The IPython Notebook in research, a Nature note at http://www.nature.
com/news/interactive-notebooks-sharing-the-code-1.16261

Installing Python with Anaconda


Although Python is an open-source, cross-platform language, installing it with the
usual scientific packages used to be overly complicated. Fortunately, there is now
an all-in-one scientific Python distribution, Anaconda (by Continuum Analytics),
that is free, cross-platform, and easy to install. Anaconda comes with Jupyter and all
of the scientific packages we will use in this book. There are other distributions and
installation options (like Canopy, WinPython, Python(x, y), and others), but for the
purpose of this book we will use Anaconda throughout.

Running Jupyter in the cloud


You can also use Jupyter directly from your web browser, without
installing anything on your local computer: go to http://try.
jupyter.org. Note that the notebooks created there are not saved.
Let's also mention a similar service, Wakari (https://wakari.io),
by Continuum Analytics.

Anaconda comes with a package manager named conda, which lets you manage
your Python distribution and install new packages.

Miniconda
Miniconda (http://conda.pydata.org/miniconda.html) is
a light version of Anaconda that gives you the ability to only install
the packages you need.

[5]
Getting Started with IPython

Downloading Anaconda
The first step is to download Anaconda from Continuum Analytics' website
(http://continuum.io/downloads). This is actually not the easiest part since
several versions are available. Three properties define a particular version:

• The operating system (OS): Linux, Mac OS X, or Windows. This will depend
on the computer you want to install Python on.
• 32-bit or 64-bit: You want the 64-bit version, unless you're on an old or low-
end computer. The 64-bit version will allow you to manipulate large datasets.
• The version of Python: 2.7, or 3.4 (or later). In this book, we will use
Python 3.4. You can also use Python 3.5 (released in September 2015)
which introduces many features, including a new @ operator for matrix
multiplication. However, it is easy to temporarily switch to a Python 2.7
environment with Anaconda if necessary (see the next section).

Python 3 brought a few backward-incompatible changes over Python 2 (also


known as Legacy Python). This is why many people are still using Python
2.7 at this time, even though Python 3 was released in 2008. We will use
Python 3 in this book, and we recommend that newcomers learn Python
3. If you need to use legacy Python code that hasn't yet been updated to
Python 3, you can use conda to temporarily switch to a Python 2 interpreter.

Once you have found the right link for your OS and Python 3 64-bit, you can
download the package. You should then find it in your downloads directory
(depending on your OS and your browser's settings).

Installing Anaconda
The Anaconda installer comes in different flavors depending on your OS, as follows:

• Linux: The Linux installer is a bash .sh script. Run it with a command
like bash Anaconda3-2.3.0-Linux-x86_64.sh (if necessary, replace the
filename by the one you downloaded).
• Mac: The Mac graphical installer is a .pkg file that you can run with a
double-click.
• Windows: The Windows graphical installer is an .exe file that you can run
with a double-click.

[6]
Random documents with unrelated
content Scribd suggests to you:
happiest are the common folk who toil
ield by day, eat scanty fare, and sleep
night unvex’d by cares of state or plots
traitorous nobles envious of a crown.
Fool. What do I say of kings? Marry, I say they were best to
watch well their daughters and their kingdoms; it needs no fool to
say so much as that. Prithee, art thou a king of the same mould as
these thou beholdest here in this place?
King Henry. At scarce nine months was I anointed king.
Fool. Truly, thou serv’st a tender apprenticeship to thy business
and I marvel the less at thy present having. [To Lear] Good nuncle,
here’s yet another king out at the elbows, one, belike, that shook his
rattle as ’t were a sceptre, and wore his porringer on ’s head where
his crown should have been.
Lear [to King Henry] And thou, too, wert a king?
King Henry. I was, but now
m I a king no longer. Edward of March
surps my title and my crown. There come
o suitors unto me, a shadow prince
ated with Madge of Anjou, strong where I
m weak, for she loves war, and weak where I
m strong, for I am joined to content
hich she, poor soul, wots little of.
King Richard. O let
s make a compact with this same content;
which shall joy the most in it, that thus
he hours shall fleet unhinder’d o’er our heads
o’er the shepherd’s gazing on his flock
om out the hawthorn shade. Or what say you,
ere it not fitter pastime to bewail
ur loss of crown and kingdom morn by morn,
ening by evening, till at last we died
grief?
King Henry. Wiser it were to strive to find
hat comfort’s left to us.
King Richard. Why, so we will.
ome, fool, be thou our numbering clock and tell
em by item all that’s left to us
nhappy kings, brothers in wretchedness.
Lear. A plague upon ye both that will not curse
he authors of your woes, that will not vex
he heavens with prayers for their undoing. Curse
n curse I’ll heap upon the heads of those
e wolves, my daughters, sprung from out my loins;
he kingdom’s ruin and their father’s bane.
[Exit raving.
Fool. Farewell to you both, for I must after him that’s such an
eager spendthrift of his curses, and may each of you come upon a
kingdom to your mind—when the sun shall smite in January.
[Exit Fool.
King Henry. A more than common grief look’d from his eye
hat roll’d so wildly in his head; pray God
e keep our wits, whatever else be lost
us.
King Richard. And I might see proud Bolingbroke
such a case as his that parted now,
deem that I could die full willingly.
King Henry. Would I were dead, an’ it were God’s good will;
ut whilst I live I ne’er will còntrive aught
evil ’gainst mine enemy, nor wish
m ill, for so weighs woe the heavier
n him invoking. Our good captain Christ
d bid us to the smiter turn the cheek
hat’s smitten yet again, nor harm him not
r all the mischiefs he doth put on us.
[Soft music heard.
King Richard. How softly steals sweet music on the soul,
utting its doors to misery and pain,
osing the senses ’gainst all foes without,
rning the hard couch unto airy down,
ssolving time in melting harmonies.
I could list forever to its sound,
ut it, or something stronger, masters me.
[Sleeps.
King Henry. Poor, changeful-hearted man that wast a king,
d captive by each wayward quick caprice,
nhappy fate call’d thee unto a throne
it did me; our kingdoms suffer’d for’t.
joy thy sleep by music underpropt,
l waking show thee as thou wert before,
crownless monarch weeping for thy crown.
[Exit King Henry.
Miranda. My heart is full of pity for these kings
anting their crowns.
Ferdinand. Those crowns had still been worn
ad they known truly what it is to be
king. O, my Miranda, only such
hat are compos’d of strength and gentleness
fair proportion mix’d, should e’er essay
he sceptre. He that may not rule himself
of all monarchs least significant.
[Exeunt.

Scene VI.
A glade in another part of the island with Ferdinand and Miranda
observed seated at the upper end thereof. Nearer at hand a group
of Athenian citizens. Enter Bottom, wearing an ass’s head.
Bottom. Masters, you will marvel to behold me here, but the very
truth of the matter is that I did fall asleep, and being asleep I did
dream, and as I did lie a-dreaming I was in a manner translated to
this place, which methinks is an island, for I did espy much water
anear as I was brought hither. But, masters, I do marvel much to
look upon you here also.
Francis Flute. Methinks, friend Bottom, you are not the sole wight
in Athens esteemed worthy translation.
Robin Starveling. How an’ we be not translated either?
Peter Quince. Robin Starveling speaks well and to the centre of the
matter. Know then, good bully Bottom, we are translated as yourself,
but methinks you have lost more in the translating than have we; is’t
not e’en so, masters all?
All. Right, good Peter Quince.
Bottom. I have lost nothing that should cause you envy, good
friends all, and so I assure you. [Brays loudly] What say you then to
my voice? Is my voice perished?
Tom Snout. No, Nick Bottom.
Bottom. I thank you, good Tom Snout, and to show you that I am
the same Nick Bottom, however my visage may appear altered, for
travel doth greatly age a man, as they say, you shall hear me wake
the echoes once again.
[Brays a second time, more loudly.
Quince. Methinks your voice, good Bottom, has lost somewhat of
sweetness.
Bottom. That’s all one, good Peter Quince, for the simple truth of
the matter is that you have no such delicate ear for fine harmonies
as I am endow’d with.
[Strokes his ears.
Quince. It doth seem so on more properer consideration, and I
had an ear that were the parallax of yours ’twere pity of my life.
All. Indeed, an’ ’twere but pity of your life, Peter Quince.
Bottom. How say you, masters, shall not we spread ourselves? [All
sit down.
Miranda. O Ferdinand, be these all mortal like
urselves? More surely I did never spy
o hideously strange a being such
he who hath the ass’s head.
Ferdinand. Nor I.
elike he hath incurr’d some wizard’s spite
nd, all unwitting, wears this semblance till
he wizard’s anger shall be spent. But see,
s fellows play upon his ignorance
nd of his strange beguilement make their sport.
Bottom. Since it is conceded by all of you that I have lost nothing
by translation, doth it not follow, moreover, that I have somewhat
gained by that same adventure?
Flute. In good truth you have gained by somewhat, Nick Bottom.
Bottom. I were an ass, indeed, an’ I had not.
Snug. And twice an ass, moreover, should he be that would go
about to steal it from you.
Bottom. Methinks that I could munch a savoury salad of thistles
with much stomach to’t.
Quince. Your thistles be a thought too biting for my stomach.
Bottom. ’Tis but likely. I was ever a choice feeder. But, masters,
was there not some matter toward, or have you assembled
yourselves but to greet me, and, as ’twere, fittingly?
Quince. You speak quite to the matter, good Bottom. That is
indeed the true end of our beginning. To behold your winsome
visage in this unwonted place is great joy to us simple mechanicals,
yet we be nevertheless bold to proclaim to you that to shave were
not amiss to one of your condition. For but bethink you, and you
were to come amongst ladies thus grievously beset with hair would
shame us all.
Snug. Mayhap in this strange part of the world ’twould be thought
matter for a hanging, and that were, indeed, a most serious
business, to my thinking.
Quince. But an’ we talk of ladies and hangings, moreover, hither
comes a monstrous little lady, as ’twere on the instant.
Enter Titania, with her train.
Titania. Where stays the gentle mortal I adore,
hose voice unto mine ear makes harmonies
elestial, and whose amiable face
thralls my heart in loving servitude?
Peaseblossom. Yonder he bides.
Moth. ’Mong others of his kind.
Cobweb. Alike, yet different.
Mustardseed. Chief mortal seen.
Titania [espying Bottom] What angel can compare unto my love?
eauty itself, beholding thee, might swoon
r envy, and the eldest sage would yield
s place to thee on th’ instant. O my love!
[Winds her arms about his neck.
hou shalt dwell with me ever. Oberon
thee is but a gaping pig, and thou
him the nonpareil of beauteous youth.
Bottom. Good mistress atomy, though you show somewhat spare
of flesh you are yet of a right comely countenance (and mine eyes
do tell me aught without spectacles), and you can speak to the point
upon occasion, as the present moment doth signify most
auspiciously.
Titania. O I could list unto thy silver tongue
l Time itself wax’d eld and perished.
Bottom. How say you, masters? Hath not mistress atomy a shrewd
manner of observation an’ she singles me out from the company of
my fellows thus compellingly?
Quince. O bully Bottom, you are, as I take it, the simple wonder of
our age.
All. Right, master Quince. Nick Bottom is become a very marvel.
Titania. Fain would I hear thy heavenly note again.
ng, wondrous mortal, while I link mine arms
bout thy peerless form, or garlands twine
dewy flowers to hang about thy neck,
hat neck, of all necks most incomparable.
Bottom [sings]
Upon the hay
Cophetua
Did waste the hours in sighing.
The beggar maid
Unto him said,
Good sir, are you a dying?
Titania. That voice would make the nightingale asham’d. [Kisses him
ow must thou leave thy fellows in this place
nd speed along with me unto my court,
here we’ll abide in loving dalliance
ntil thy mortal part’s with spirit mix’d.
aseblossom! Cobweb! Moth! and Mustardseed!
Peaseblossom. Ready.
Cobweb. And I.
Moth. And I.
Mustardseed. And I.
All. Your hest,
ur queen, is still our duty and delight.
Titania. Attend us to the court, and evermore
ve special heed unto this gentleman,
nticipate his ev’ry wish and feed
m with the choicest cates the isle doth yield.
[Exeunt Titania and Bottom, attended by train.
Quince. Were this but told in Athens, now, ’twere not believed by
aught, but we accredited liars all of the first water, and so esteemed.
All. ’Twere indeed but so, and truly, Peter Quince.
Quince. Therefore I hold that (an’ we once more come by our own
firesides in Athens), we were best make no words of the happenings
we have beheld but now, lest we be cried upon in the public streets
as those that be counted no true men.
All. That were to shame us, every mother’s son.
Quince. Why you speak the very gizzard of the matter, my masters
all, and we will be silent in such wise as I did perpetuate, and as for
Nick Bottom, let his goblin mistress do with him as she listeth, for
methinks we are well rid of his company, being, for ourselves,
nothing loose-minded but sober, virtuous citizens all.
All. That are we, Peter Quince, and we thank God for’t.
Enter Puck, unperceived, who tweaks Quince
violently by the nose and exits.
Quince. O masters, which of you—
Is suddenly twitched aside by Puck. Re-enters
with a lion’s head on his shoulders.
All. God defends us, Peter Quince.
Quince. Masters, it ill becomes you as sober citizens of Athens to
treat one of yourselves thus unseemly. Am not I a simple workman
like the rest of you? Is it not my very own voice that you hear but
now? [Roars.
All. God for his mercy.
[Exeunt all but Quince.
Quince. These be strange manners; an’ I were a very lion, though
being of a truth of a most lamblike perdition, they could not have
fled from me with greater speeding. I will e’en after them to taste
the reason of their knavery.
Enter Puck.
Puck. Now will I set these patches by the ears,
aking such monsters of their simple selves
severally shall fright them when they see
ch in the other’s fearful eyeball glass’d.
[Exit Puck.
Re-enter Quince.
Quince. And I can spy but one of my neighbours in this
predestinated place I’ll be hanged.
Re-enter Starveling, with an owl’s head.
Quince. Bless us, Robin Starveling, what wizardry do I spy in you?
Starveling. Wizardry, an’ you call it, Peter Quince? Look to your
own head an’ you would find out wizardry. There’s naught strange in
me.
Re-enter Snug, with a bear’s head.
Quince and Starveling. Save us, good Snug, how art thou
transmogrified!
Snug. Not so, neither, neighbours both. I am but Snug the joiner,
as you might behold him of any working day, but you twain,
methinks, are most marvellously encountered.
Quince and Starveling. Speak for yourself, Master Snug: we are the
same as you have known us ever.
Quince. That is, I am the same, but Master Starveling is quite
other than the simple man he was.
Starveling. Thou liest, Peter Quince. I am but plain Robin
Starveling, but you are become a very monster.
Re-enter Snout, with a deer’s head and horns.
Quince. Good masters three, you are enchanted, and pity o’ my
life it is. ’Tis I alone that doth remain as much mankind as I was
ever.
Snout. An’ you count yourself the proper likeness of a man you
are most horribly mistook, and so it is, Peter Quince.
Re-enter Flute, with the head of a crocodile.
Flute. O neighbours all, what behold I here? What sorcerer has
thus exorcised upon you? O could you be spy upon yourselves to
know how unlike you are to plain citizens like me.
Quince. A plain man, say you. Forsooth, yours is a very fearful
manner of plainness, Francis Flute. But look at me, masters all, and
you would gaze upon a plain man.
Starveling. Nay, look on me, in his stead.
Snout. Not so, but on me.
Snug. These be liars, every mother’s son. Look upon me, I say,
Francis Flute.
Flute. Masters, hear but the simple truth. You are all of you
deceived and have suffered most horrible enchantment, every
mother’s son of you but me. Heaven help you, neighbours, and undo
the spell that each and every one may become as I am.
[Gnashes his jaws fearfully.
All. That were most dire affliction of any that be in the varsal
world, Francis Flute.
Flute. And you were not something other than simple mankind I
could try conclusions with you that speak thus enviously. Indeed, I
am something that way toward, but now.
[Exeunt Omnes, fighting.
Enter Puck.
Puck. Thus have I put the simple senses all
these rude knaves sorely distraught, for each
oth fear the other, deeming him the prey
dark enchantment, while himself believes
mself none other than he was at first

Lord, how simple mortals be,


And it much doth pleasure me
To behold them all distraught;
Each in fairy toils is caught,
There to bide at my good will,
Roaring, growling, fighting still.
[Exit Puck.
Ferdinand. How like you this, Miranda? Hath not he,
he gamesome elf, made merry mischief so
ongst these dull wits that scarce may they once more
egain their sometime selves and liberty.
Miranda. ’Twas merry, sooth, yet I could wish the spell
ssolv’d that made them fearsome to themselves,
nd enemies that once were friends. He that
ath friends hath treasure, more than wealth of Ind,
nd he that hath not still is poor indeed,
hough all the gold of Ophir ’long’d to him.
Enter Jaques, laughing.
Jaques. Though I be sworn to sadness it doth make
e gladsome ’gainst my disposition
note the antics of these greasy fools
Athens, pent within the glade where I,
unobserv’d, have play’d the spy upon
m this full hour. How like these fustian churls
e to their fellows of the scepter’d throne,
he ermine robe, the ’broider’d chasuble.
s habit makes the man, the wearer’s naught.
he fool, when he is naked, shows as sage
the philosopher so furnished;
he lout’s bare hide’s no worser than the king’s,
nd, when their pride is fondly touch’d, all men
e brothers. Did not each Athenian wight
eholding all his fellows in their guise
ost strange and horrible, yet deem himself
rch’d high above the reach of wizardry,
nd sole possessor of a countenance
ch as is worn ’mongst ordinary folk?
y sides do ache with mirth when I bethink
e of these simple churls, and of their kin
y Adam, in high places set, how each,
o matter what his state, doth ne’er perceive
mself glass’d in his fellow’s eye, but paints
stead a portrait in fair colours mix’d,
lls it his likeness, and would have the world,
hat knows him what he is, declare its truth
oth in the general and particular.
his globe is peopl’d with philosophers
nd fools, methinks, by which I mean the wise
e the sole wearers of the motley coat
nd all men else do owe the cap and bells.
he lover is a fool who doth proclaim
s mistress is perfection; the maid,
ho thinks her swain compact of truth; the king,
ho stakes his crown upon a battle’s point;
he soldier, who for glory gives his life
nd dies, a forfeit to’t; the tonsur’d saint,
ho vows to heaven that which ’longs to men.
I could moralize upon this theme
n hour by the clock, with still grave matter left
r melancholy contemplation.
[Exit Jaques.
Miranda. Yon sober suited wight, meseems, doth make
play of sadness.
Ferdinand. So, in sooth, he doth.
s wisdom rings but hollowly, and all
s speech declares a studied wilfulness
ch as we note in him who acts a part
hat finds no smallest likeness in himself.
Soft music heard, followed by a dance of elves.
[Exeunt Ferdinand and Miranda.

Scene VII.

Still another part of the island.

Enter Prospero.
Prospero. Now have I ’complish’d that I did intend,—
spers’d Miranda’s sadness utterly,
nd, for a brief space, made the airy dreams
Master Shakescene take on form again
erst in other lands and climes, that so
hese married lovers might be entertain’d
ll pleasingly, and gather from the hours
pent in this isle of summer, honey’d sweets
r fond remembrance in the tide of time.
y Ariel! What, Ariel, I say! [Enter Ariel.
hanks, gentle Ariel, who hast again
one all my bidding. But for thee my art
ad halted ere its best. Once more receive
y thanks, who am much bound to thee.
Ariel. This
time,
ood master Prospero, I serv’d for love
ot duty, and I count your thanks reward
fullest measure. And there be nothing else
u would of me, then, Prospero, adieu.
ospero. Adieu, gentlest of spirits, Ariel.

[Exit Ariel.
Thunder heard and Prospero vanishes.

Scene VIII.

A room in the palace at Naples.


[Enter Ferdinand and Miranda.
Miranda. O Ferdinand, my love, last night I slept
nd sleeping dream’d, and in my dream I saw
he isle where first you knew me, where we told
ch to the other our fond loves. Methought
was by you companion’d and the hours
d move to music while there pass’d before
ur wond’ring eyes, as for our sole delight,
many folk, strange sorted, who did talk
gether, and at whiles as ’twere a play
nd we beholding it. ’Twas wondrous strange.
Ferdinand. O, my Miranda, sure some power we wot
ot of doth play with us as we at chess
o move the pieces this way first and that,
ecause our will is to’t. Know then that I
d dream the fellow unto yours (if it
very truth were that and nothing more).
ke you, I vis’ted that sweet spot, with you
eside the while, and did behold, as on
stage a company of players strut
heir hour or two, a band of merry folk
ith some that wept and cried out upon fate.
ho knoweth, my Miranda, what doth hap
us when we do sleep? At whiles we note
slumber tokens of a life apart
om this, alike, yet not alike, and who
ay say how far the spirit wanders when
he body sleeps?
Miranda. Would all my dreams were like
this we’ve wak’d from, for ’twas sweet, yet sad,
nd not so sad but that ’twas sweet the more.
would it were to dream again.
Ferdinand. Who knows,
weet Saint Miranda, but it will return?
Soft music again heard.
[Exeunt Ferdinand and Miranda.
II

THE MERCHANT OF VENICE:

ACT SIXTH
THE MERCHANT OF VENICE:
ACT SIXTH

Scene I.

Venice. A street.
Enter Shylock, followed by a rabble of shouting citizens.
First Citizen. Shylock, how speeds thy business at the court?
here is the pound of flesh thou covetest?
Second Citizen. How likest thou the judge from Padua?
Third Citizen. Eh, Jew, an upright judge! thou hast my lord
he duke to thank for thy poor life. Had I
ut been thy judge a halter had been thine,
nd thou had’st swung in’t, yet, beshrew my life,
were pity that good Christian hemp were stretch’d
hang a misbegotten knave like thee.
Fourth Citizen. Shylock, thou infidel, thou should’st have had
he lash on thine old back ten score of times
e they had suffer’d thee from out the court.
Fifth Citizen. A beating shall he have, e’en now, the knave.
[Beats Shylock.
Shylock [striking about him angrily] Aye! kill me, dogs of Christians,
an’ ye will!
eseems the Jew hath no more leave to tread
he stones on Christian streets; he may not breathe
he air a Christian breathes, nor gaze uncheck’d
pon the Christian’s sky; he hath no part
lot in anything that is, unless
Christian please to nod the head. I hate
, brood of Satan that ye are! May all
he plagues of Egypt fall upon ye, dogs
Christians; all the pains—
Fourth Citizen. Nay, gentle Jew,
s said thou must become a Christian, straight;
d Shylock, turn perforce, a “Christian dog!”
ow, greybeard infidel, how lik’st thou this?
Shylock. Eternal torments blister him that asks.
[Exit Shylock, raving.
Second Citizen. A sweet-fac’d Christian will our Shylock make.
would that I might be his cònfessor,
lay such swingeing penance on the knave
scarce would leave him space to sup his broth
mid the pauses of his punishment.
[Exeunt citizens, with shouts.

Scene II.

Venice. A Room, in Shylock’s House.


[Enter Shylock and Tubal.
Tubal. How now, Shylock! What bitter woe looks from thy face?
What has chanced to thee in the Christian’s court to make thee thus
distraught?
Shylock. O Tubal, Tubal, there dwells no more pity in the Christian
breast than there abides justice therein. I stood for justice and mine
own, before them all; before that smiling, smooth-faced judge from
Padua, and with those false smiles of his he turned against me the
sharp edge of the law. He forbade the shedding of one drop of the
merchant Antonio’s blood—naming therefor some ancient law, musty
for centuries, and that still had gathered dust till it would serve to
bait the Jew with—and so I lost my revenge upon Antonio. More
than that, good Tubal, I lost everything I had to lose.
Tubal. Lost everything! Now, by our ancient prophets, this is woe
indeed.
Shylock. Aye, good Tubal. The half my goods are now adjudged
Antonio’s; the other half, upon my death, goes to the knave,
Lorenzo; that same he that lately stole my ducats and my daughter.
Tubal. And merry havoc will he and thy daughter Jessica make of
thy treasure, Shylock.
Shylock. But there is greater woe to come, good Tubal. To save
this poor remainder of a life have I this day sworn to turn a
Christian.
Tubal. Thou, turn Christian! O monstrous deed! Our synagogue
will be put to everlasting shame for this. Nay, good Shylock, it must
not be. It must not be.
Shylock. Have I not said that I am sworn on pain of life? They
would e’en have had my life almost in the open court had I not so
sworn. But hear me, Tubal; I will not die till that I have bethought
me of some secret, sure revenge upon Antonio, or failing this, upon
the taunting, sneering fool they call Gratiano, whom I do loathe e’en
as I loathe Antonio. Moreover I would gladly do some deadly hurt
unto the accursed Paduan judge, an’ it might be so.
Tubal. Then wilt thou still be Hebrew at the heart, good Shylock?
Shylock. How else while yet I bear remembrance of my wrongs?
Have not many of our chosen people done this selfsame thing for
ducats or for life? Kissed the cross before men’s eyes, but spurned it
behind their backs? As I shall do, erewhile. But, O good Tubal, the
apples of Sodom were as sweet morsels in the mouth unto this that
I must do.
Tubal. Hebrew at heart, albeit Christian of countenance.
y, Shylock, it is well. It is well.
[Exeunt.

Scene III.

Venice. Interior of Saint Mark’s.


Organ music heard. Enter a company of noble Venetians with the
Duke and his train, accompanied by Bassanio, Portia, Antonio,
Gratiano, Nerissa and others. Following these, at a little distance,
appear Lorenzo and Jessica, the latter gorgeously attired. The
company pauses before the font. Shylock enters from the left, led
forward by a priest. His gaberdine has been exchanged for the
Christian habit, and in his hand is placed a crucifix.
Duke. Old Shylock, art thou well content to do
thus we have ordain’d, which is, that thou
enounce thine ancient Jewish faith, repent
hy sins, and take the holy, solemn vows
Christian takes when on his brow the drops
ptismal glister, and be nam’d anew
ter the Christian custom of our land?
Shylock. Most noble duke, I am content, and do
ereby renounce my nation and my faith,
nd, which is more, raze out of mind the name
hat I have borne these three-score heavy years,
nce it is thy command.
Duke. Cristofero
alt thou be call’d hereafter. Now, good priest,
hine office do with ceremonies meet,
nd make this greybeard Jew a Christian straight.
Solemn music heard, after which Shylock is baptized by the priest,
Antonio at the command of the Duke standing godfather to the
Jew, who makes the required responses in a low voice. While he is
still kneeling the company converse in an undertone.
Gratiano. I much mislike this new made Christian’s face
or would I trust Cristofero for all
s Christian name and meekly mutter’d vows.
Portia. Nay, Gratiano, question not the heart
or rudely draw aside the veil that speech
angs ever ’fore the spirit. Who may say
hat e’en the best among us keeps a faith
yal to every smallest clause, or does
ot slip at whiles amid the thousand small
equirements of the law. And yet, we do
mplore a gentle sentence on these sins
ours, a pardon that shall make us whole.
for ourselves, then trebly for the Jew
ew come, bewilder’d, to our Christian creed.
Antonio. There will be space enow to doubt the Jew
rn’d Christian, Gratiano, when he shall
ve cause for doubt. ’Twere scantest charity
l then, to bear with him, as we do bear
urselves unto our fellow Christians all.
bitter lesson hath he lately conn’d,
nd he were mad indeed that should neglect
profit by’t.
Gratiano. Belike, belike ’tis thus,
ut yet I do not like Cristofero’s looks;
not be argu’d out of that, i’ faith,
nd say’t again, I much mislike his favour.
Nerissa. Peace, Gratiano, dost not note the duke
ommands to silence, and would speak once more?
hou wilt be ever talking, as thy wont.
Duke. Cristofero, thou bear’st a Christian name
om this day forth. Then look to’t that thou dost
all things as a Christian, not as Jew.
Shylock. In all things as a Christian. Yes. [Aside] Why that’s
evenge! Revenge!
Duke. So must thou quit thy house
Jewry, dwell mid Christian folk, and go
ith Christian folk to church on holy days,
nd wear henceforth the cross thou did’st disdain.
ost hearken unto us, Cristofero?
Shylock. I hear but to obey, dread duke; and thank
hee for thy clemency to me, once Jew,
ut now, within this very selfsame hour,
gasping new born Christian, all unschool’d
duties other Christians know full well,
t earnest still, to act the Christian’s part,
ith hope to better his ensample set.
Gratiano [aside to Bassanio] For all thy gentle Portia saith but now,
ike not such smooth terms from out those lips.
Bassanio [aside] Peace, Gratiano, let him say his say,
e cannot now do aught to injure thee.
[Exeunt Duke and train with Antonio and
friends. Lorenzo and Jessica come forward.
Jessica. How now, good father Cristofero; what a pair of Christians
are we both. Only there’s this difference betwixt us, good father. I
am a Christian for love of a husband and you have turned a Christian
for love of your ducats.
Shylock. Ungrateful daughter; Why did’st thou go forth from my
house by night and rob thy grey-haired father of his treasure?
Jessica. Why? That’s most easy of answer. Why, because I desired
a Christian husband and there was no coming by my desire save by
secret flight from your most gloomy chambers; and since neither my
Christian husband nor your daughter Jessica could by any kind of
contriving live upon air alone, we had, perforce, to take with us
some of your ducats for the bettering our condition. Speak thou for
me, Lorenzo. Was it not e’en so?
Lorenzo. Old man, I am sorry for that I was forced to take from
you your daughter and your ducats against your good pleasure, but
I must tell you that I loved her as myself [Aside] nay, much more,
my Jessica,—and by reason of this great love of mine, and because
of your exceeding hatred towards all Christians did I take her from
your house. And since, moreover, as the maid very truly says, there’s
no living i’ the world without the means to live, because of this did
we make shift to take with us from your house such means, as well
advised you would not have your daughter lack for food and suitable
apparel, and since we are now Christians all, what matters it?
Shylock [slowly] Ay, what matters it? We are now Christians all, as
thou sayest, and, I remember me that I have heard it said it is a
Christian’s duty to forgive all who have wronged him. Therefore I
forgive you, Jessica—for robbing your old father; and you, Lorenzo, I
forgive—for stealing my daughter. You are each well mated. But I
would be alone a while. Go, good Jessica. Go, son Lorenzo.
[Exeunt Lorenzo and Jessica.
Shylock [alone] A curse pursue the twain where’er they go.
Christian-Jewish curse, since that should be
eightier than either singly. Would that I
ght see them dead before me, while I live,—
ch love I bear my daughter, and my son.
[Gazes about the church.
hese be the images of Christian saints
hom I must bend the knee before when men
ok on. And here the Virgin; here the Christ.
ow must I kneel; a hundred eyes perchance,
er at me through the gloom. A hundred eyes
ay see me kneel, yet shall they not perceive
he scorner of the Christian hid within
he humble figure of the man who kneels.
ow, by the prophets, whom I reverence,
nd by these Christian saints whom I do scorn,
swear to nourish my revenge till those
deepest hate are dead, or sham’d before
heir fellows. But how this may be, I know
ot yet, for all the way were dark as night
efore me, save that my revenge burns red.
[Choir heard chanting in a distant chapel.
[Rises from his knees.
ood fellow Christians, it may hap the Jew
rn’d Christian, shall yet do a harm to ye.
ehind Cristofero’s mask is still the face
Shylock; in his breast the heart unchang’d.
[Choir heard chanting Judica me Deus.
a, my good fellow Christians, I do thank
for that word, and hug it to my heart.
enceforth it shall be mine, when I do pray,
ot to thy Christ, but unto Israel’s God!
ive sentence with me, O my God; defend
y cause against the hosts that wrought me ill.”
[Choir in the distance, responding Amen.

[Exit Shylock.
NOTE BY WILLIAM J. ROLFE, Litt.D.
It is a tribute of no slight significance to Shakespeare’s skill in the
delineation of character that we instinctively regard the personages
in his mimic world as real men and women, and are not satisfied to
think of them only as they appear on the stage. We like to follow
them after they have left the scene, and to speculate concerning
their subsequent history. The commentators on Much Ado, for
instance, are not willing to dismiss Benedick and Beatrice when the
play closes without discussing the question whether they probably
“lived happily ever after.” Some, like Mrs. Jameson and the poet
Campbell, have their misgivings about the future of the pair, fearing
that “poor Benedick” will not escape the “predestinate scratched
face” which he himself had predicted for the man who should woo
and win that “infernal Até in good apparel,” as he called her; while
others, like Verplanck, Charles Cowden-Clarke, Furnivall, and
Gervinus, believe that their married life will be of “the brightest and
sunniest.”
Some have gone back of the beginning of the plays, like Mrs.
Cowden-Clarke in her Girlhood of Shakespeare’s Heroines, and Lady
Martin (Helena Faucit) in her paper on Ophelia in Some of
Shakespeare’s Female Characters.
Others, like Mr. Adams, have made the experiment of continuing a
play of Shakespeare in dramatic form. Ernest Renan, in France, and
Mr. C. P. Cranch, in this country, have both done this in the case of
The Tempest, mainly with the view of following out the possible
adventures of Caliban after Prospero had left him to his own devices.
These and similar sequels to the plays are nowise meant as
attempts to “improve” Shakespeare (like Nahum Tate’s version of
Lear, that held the stage for a hundred and sixty years) and sundry
other perversions of the plays in the eighteenth century, which have
damned their presumptuous authors to everlasting infamy. They are
what Renan, in his preface, calls his Caliban,—“an idealist’s fancy
sketch, a simple fantasy of the imagination.”
Mr. Adams’s Sixth Act of The Merchant of Venice is an experiment
of the same kind; not, as certain captious critics have regarded it, a
foolhardy attempt to rival Shakespeare. It was originally written for
an evening entertainment of the “Old Cambridge Shakespeare
Association.” No one in that cultivated company misunderstood the
author’s aim, and all heartily enjoyed it. I believe that it will give no
less pleasure to the larger audience to whom it is now presented in
print.
Transcriber’s Note:
Words may have multiple spelling variations or inconsistent
hyphenation in the text. These have been left unchanged. Obsolete
words, alternative spellings, and misspelled words were not
corrected.
Obvious printing errors, such as backwards, reversed, upside
down, or partially printed letters and punctuation, were corrected.
Final stops missing at the end of sentences and abbreviations were
added. Duplicate words at line endings were removed. Right-aligned
stage directions were adjusted so that all are preceded by an open
bracket.
*** END OF THE PROJECT GUTENBERG EBOOK A MOTLEY JEST ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.

You might also like