How to use Jupyter Notebook effectively with Magic commands?

Posted by Mayur


Data scientists and data analysts frequently utilise Jupyter Notebooks as a tool to begin their analyses. And there are a few important Jupyter notebook tricks or commands that are hardly ever used by the community.

In this post, we’ll execute commands which will make us a better user of Jupyter notebooks. Only pre-requisite to use magic commands is to install Ipython-kernel

    pip install ipykernel

Time taken to execute a block of code? %%time

    count = 0
    for i in range(10000):
        count += i
    CPU times: user 1.39 ms, sys: 0 ns, total: 1.39 ms 
    Wall time: 1.4 ms

Time taken to execute each line of code? %time

    %time print("a")
    %time print("b")
    CPU times: user 35 µs, sys: 0 ns, total: 35 µs 
    Wall time: 37.9 µs

    CPU times: user 8 µs, sys: 0 ns, total: 8 µs 
    Wall time: 9.06 µs

How to push code of your Jupyter cell into Python file? %%writefile

    def add(a, b):
        return a+b
    add(5, 6)

In the above code, the function add or the lines below “%%writefile” is pushed into file. It will overwrite existing file or create a new file.

How to load the content of python file into Jupyter cell? %load


On running above code, the contents of the file will be loaded into jupyter cell as follows

    # %load
    def add(a, b):
        return a+b
    add(5, 6)

How to run a python file in Jupyter cell? %run


How to check the environment variables? %env

    {'ELECTRON_RUN_AS_NODE': '1',  'USER': 'mayur',  'LANGUAGE': 'en_IN:en',  'TEXTDOMAIN': 'im-config',  'XDG_SEAT': 'seat0',  'XDG_SESSION_TYPE': 'x11',  'SSH_AGENT_PID': '1711',  'SHLVL': '1',

How to set environment variable? %set_env

    %set_env NEW_PATH=/usr/bin/python1

You can verify the newly created environment variable using %env.

How to find all the initialized variables in Jupyter? %who

    count i

How to all the variables based on datatype? %who datatype

    %who int
    count i

How to find all the available magic commands? %lsmagic


How to write html code in Jupyter cell? %%html

           <strong>This is %%HTML magic commands</strong>

    This is %%HTML magic commands

Find the above post as jupyter notebook here: github

Find the above post as youtube video here: YouTube


Feedback is welcomed 💬