What are the magic commands?
Magic commands are special commands that can help you with running and analyzing data in your notebook. They add a special functionality that is not straight forward to achieve with python code or jupyter notebook interface.
Magic commands are easy to spot within the code. They are either proceeded by % if they are on one line of code or by %% if they are written on several lines.
In this article, I am going to list magic commands that are used most often and show practical examples of how to take an advantage of the functionality they provide.
1. List all magic commands.
Let’s start by listing all possible magic commands that you can use in the notebook.
%lsmagic
If you run the line above in your notebook you should get a list similar to the screenshot below. These are all the commands available to you. We will go through just a fraction of them in this article.
2. Run a file.
You can run a python file from your jupyter notebook using the following code.
%run <file name>
Imagine that you have a file hello.py with the following content:
def hello_world():
print('Hello, world')
hello_world()
You can run the following command in the notebook to run the file.
%run hello.py
3. Get an execution time.
You can time the execution of the code using the time command.
%%time
<your code>
Let’s generate 1 000 000 random numbers and see how long it takes.
%%time
import random
for i in range(0, 1000000):
random.random()
4. List all variables.
There is a magic command that allows you to list all variables that are defined within the current notebook.
%who
You can pass it a data type after command name to list only variables of the specific data type.
To illustrate this let’s define a string variable and two int variables.
var_1 = 1
var_2 = 'hello'
var_3 = 100
Now we can list all strings with:
%who str
Or all integers with:
%who int
#data-science #programming #machine-learning #artificial-intelligence #jupyter-notebook