Installing Python Packages in Jupyter Notebook - Right Way

I really suggest all the Jake’s blog and its book on Data Science (freely available on his website), it covers a lot of ground on python, visualisation, ML and how other general python cases. Jake is also a core contributor of “scikit-learn: machine learning in Python”!
Installing Python Packages from a Jupyter Notebook” is helpful to have self-contained jupyter notebook with its dependencies packed in.
This works better if you are running a jupyter notebook and its kernel is a python from a virtualenviroment. And you should definitively do this! Don’t pollute your system installation.
In the link there is also a discussion on conda that I don’t (yet) use.
Note the different python path on the commands output, they point to different python executables.

The gist of it is (quoting Jake’s blog here):

If you’re using the Jupyter notebook and want to install a package with pip , you similarly might be inclined to run pip directly in the shell:

# DON'T DO THIS
!pip install numpy
Requirement already satisfied: numpy in 
/Users/jakevdp/anaconda/envs/python3.6/lib/python3.6/site-packages

For various reasons that I’ll outline more fully below, this will not generally work if you want to use these installed packages from the current notebook, though it may work in the simplest cases.

Here is a short snippet that should generally work:

# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install numpy 
Requirement already satisfied: numpy in 
/Users/jakevdp/anaconda/lib/python3.6/site-packages
2 Likes

Big fan of Jake here, too! :wink: