How to Automatically Import Your Favorite Libraries into IPython or a Jupyter NotebookNo more typing “import pandas as pd” 10 times a dayWill KoehrsenBlockedUnblockFollowFollowingFeb 14If you often use interactive IPython sessions or Jupyter Notebooks and you’re getting tired of importing the same libraries over and over, try this:Navigate to ~/.
ipython/profile_defaultCreate a folder called startup if it’s not already thereAdd a new Python file called start.
pyPut your favorite imports in this fileLaunch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!Here are the steps in visual form.
First, the location of start.
py:Here is the contents of my start.
py:Now, when I launch an IPython session, I see this:We can confirm that the libraries have been loaded by inspecting globals() :globals()['pd']<module 'pandas' from '/usr/local/lib/python3.
py'>globals()['np']<module 'numpy' from '/usr/local/lib/python3.
py'>We’re all good to use our interactive session now without having to type the commands to load these libraries!.This also works in Jupyter Notebook.
NotesThe file can be named anything ( start.
py is easy to remember) and you can have multiple files in startup/.
They are executed in lexicographical order when IPython is launched.
If you’re running this in a Jupyter Notebook, you won’t get a cell with the imports so when you share the notebook, make sure to copy over the start.
py contents into the first cell.
This will let people know what libraries you are using.
(As an alternative, you can use the default_cell Jupyter Notebook extension I wrote.
)If you work on multiple computers, you’ll have to repeat the steps.
Make sure to use the same start.
py script so you get the same imports!Thanks to this Stack Overflow answer and the official docsThis is certainly not life-changing (unlike writing about data science) but it saves you a few seconds every time you start IPython.
It’s also useful as a demonstration of how you can customize your work environment to be as efficient as possible.
There are many other tips you can find by reading documentation (such as for IPython magic commands), experimenting on your own, or even following helpful Twitter accounts.
If you find yourself frustrated with an inefficiency like typing import pandas as pd ten times a day, don’t just accept it, find a better way to work.
As always, I welcome feedback and constructive criticism.
I can be reached on Twitter @koehrsen_will.