Jupyter Notebook – Cell Magic Functions
In this article, we will cover Cell Magic Functions in Jupyter Notebook we will discuss various functions. But first, we look at what Jupyter Notebook and Cell Magic functions and why we use them. There are a lot of cell magic functions but in this article, we discuss the most commonly used cell magic functions.
Jupyter Notebook
The Jupyter Notebook is the original web application for creating and sharing computational documents that contain live code, equations, visualizations, and narrative text. It offers a simple, streamlined, document-centric experience. Jupyter has support for over 40 different programming languages and Python is one of them.
There are two types of Magic Functions:
- Cell Magic Functions
- Line Magic Functions
Cell Magic Functions
Cell Magic functions are special commands that allow the user to modify the behaviour of a code cell explicitly. Cell Magic functions have the prefix ‘%%’ followed by the command name. Cell magic functions serve various tasks and customizations which we discuss thoroughly further in this article.
Advantages of Cell Magic Functions
Limitations of Cell Magic Functions
- Dependencies of different kernels or environment
- Ambiguity occurs if too many cell magics are used and can cause potential conflicts
- Hard to remember the syntax of different cell magic functions
Table of Cell Magic Functions
Cell Magic Function |
Description |
---|---|
%%bash |
Run cells with bash in a subprocess. |
%%capture |
run the cell, capturing stdout, stderr, and IPython’s rich display() calls. |
%%html |
Render the cell as a block of HTML |
%%javascript or %%js |
Run the cell block of Javascript code |
%%latex |
Render the cell as a block of LaTeX |
%%markdown |
Render the cell as Markdown text block |
%%perl |
Run cells with perl in a subprocess. |
%%pypy |
Run cells with pypy in a subprocess |
%%python |
Run cells with python in a subprocess |
%%python2 |
Run cells with python2 in a subprocess. |
%%python3 |
Run cells with python3 in a subprocess |
%%ruby |
Run cells with ruby in a subprocess |
%%script |
Run a cell via a shell command |
%%sh |
Run cells with sh in a subprocess |
%%svg |
Render the cell as an SVG literal |
%%writefile |
Write the contents of the cell to a file. |
Cell Magic Functions along with examples
1. %%time:
Measures the execution time of the entire cell
Example:
Python3
% % time for i in range ( 1000000 ): pass |
Output:
CPU times: user 19 ms, sys: 2 ms, total: 21 ms
Wall time: 24.6 µs
2. %%timeit:
Measures the execution time and performs multiple runs for more accurate timing.
Example:
Python3
% % timeit sum ( range ( 100 )) |
Output:
584 ns ± 6.66 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
3. %%writefile:
Writes the content of the cell to a file with the specified filename.
Example:
Python3
% % writefile my_script.py print ( "Hello, world!" ) |
Output:
Writing my_script.py
4. %%markdown or %%md:
Renders the content of the cell as Markdown.
Example:
Python3
% % markdown # This is a Markdown Heading * This is a bullet point |
Output:
Renders as formatted Markdown text.
5. %%bash:
Allows you to run Bash shell commands within the cell.
Example:
Python3
% % bash ls - l |
Output:
total 24568
-rw-r--r-- 1 root root 761835 Oct 9 16:14 bodyPerformance.csv
drwxr-xr-x 5 root root 4096 Oct 10 18:00 catboost_info
-rw-r--r-- 1 root root 179414 Oct 10 18:01 CatBoost.ipynb
-rw-r--r-- 1 root root 210263 Oct 9 17:47 catboost_model.pkl
-rw-r--r-- 1 root root 88229 Oct 16 14:10 Correlation.png
-rw-r--r-- 1 root root 6706326 Oct 26 18:30 LightGBM1.ipynb
-rw-r--r-- 1 root root 1039742 Oct 9 18:18 LightGBM .ipynb
-rwxrwxrwx 1 root root 15583484 Sep 26 16:25 LightGBM.ipynb
-rw-r--r-- 1 root root 51773 Oct 19 14:12 model.bin
-rw-r--r-- 1 root root 62296 Oct 19 13:59 model.h5
-rw-r--r-- 1 root root 23 Oct 26 18:27 my_script.py
-rw-r--r-- 1 root root 447296 Oct 26 17:50 placementdata.csv
6. %%html:
This cell magic function renders contents of code cell as html script.
Example:
Python3
% % html <font size = 10 color = 'hotpink' >Hello World< / font> |
Output:
Renders as HTML
7. %%debug:
Activates the interactive debugger for the cell.
Example:
Code executations
Python3
% % debug x = 5 y = 0 result = x / y |
Output:
NOTE: Enter 'c' at the ipdb> prompt to continue execution.
> <string>(2)<module>()
ipdb> c
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
ZeroDivisionError: division by zero
8. %%javascript:
Allows you to execute JavaScript code within the cell.
Example:
Python3
% % javascript alert( "This is a JavaScript alert!" ) |
Output:
Executes the JavaScript code and displays an alert.
9. %%latex:
Renders LaTeX equations and expressions in the cell.
Example:
Python3
% % latex $e^{i\pi} + 1 = 0 $ |
Output:
Renders as a LaTeX equation.
Screenshot Output:
10. %%matplotlib
Enable inline plotting of Matplotlib figures in Jupyter Notebook
Example:
Python3
% matplotlib inline import matplotlib.pyplot as plt # Generate some data data = [ 1 , 2 , 3 , 4 , 5 ] # Create a plot plt.plot(data) plt.title( "Simple Line Plot" ) plt.xlabel( "X-axis" ) plt.ylabel( "Y-axis" ) plt.show() |
Ouput:
11. %%sql
%sql allows you to execute SQL queries directly in a code cell when using a SQL kernel:
Example:
Python3
% load_ext sql % sql sqlite: / / / mydatabase.db % % sql SELECT * FROM Employees WHERE department = 'Sales' ; |
Output:
Runs the sql query
There are a lot of cell magic functions which you can find in the official documentation of python and try it on your own, in this article we have only covered the most commonly used cell magic functions.