A dash of magic
Magic commands are a set of convenient functions in Jupyter Notebooks that are designed to solve some of the common problems in standard data analysis. You can see all available magics with the help of %lsmagic
.
Magic commands are of two kinds: line magics, which are prefixed by a single %
character and operate on a single line of input, and cell magics, which are associated with the double %%
prefix and operate on multiple lines of input. Magic functions are callable without having to type the initial % if set to 1.
Let’s look at some of them that might be useful in common data analysis tasks:
- % pastebin
%pastebin uploads code to Pastebin and returns the URL. Pastebin is an online content hosting service where we can store plain text like source code snippets and then the URL can be shared with others. In fact, Github gist is also akin to pastebin albeit with version control.
Consider a python script file.py
with the following content:
Using %pastebin in Jupyter Notebook generates a pastebin url.
- %matplotlib notebook
The %matplotlib inline
function is used to render the static matplotlib plots within the Jupyter notebook. Try replacing the inline
part with notebook
to get zoom-able & resize-able plots, easily. Make sure the function is called before importing the matplotlib library.
The %run
function runs a python script inside a notebook.
- %%writefile
%%writefile
writes the contents of a cell to a file. Here the code will be written to a file named foo.py and saved in the current directory.
The %%latex function renders the cell contents as LaTeX. It is useful for writing mathematical formulae and equations in a cell.