Jupyter Notebooks or Jupyter Labs are everywhere at the moment. And rightly so; there are so many things you can do with them, such as this, this and this. These three pages were just the first three returned after searching google for
This post is a simple example of one of the ways I’ve started using notebooks recently. One of the things I have been doing to help my scripting is to build a set of commonly called/used functions that I have written, and to import them into the notebook. This way, if you do a specific bit of regex regularly or perhaps a graphing function in Pandas you, a) don’t need to re-write it again and again, and, b) you don’t need to spend time trawling over old notebooks to find that useful function and then cutting and pasting the function(s) in.
Super simple example
Let’s assume that all code is in the same folder on your computer; it doesn’t have to be – you’ll just need to change the pointers. As an example, write a script called standard_functions.py and in it write these two lines:
def hello(name): print("hello", name)
and then save. Next, open a blank notebook in the same location and run the command:
%run -i standard_functions.py
It will run your standard_functions.py file. In the next cell type:
You will get the following back:
This might be helpful if you have a particularly large standard_functions.py file to see all your ‘standard_functions’; there is a neat command to help with this:
When the cell is run, it brings all those functions into a cell (and shows it unrun). This enables you to use or to slightly adapt without changing the master standard_functions.py file. Then, run the cell (again):
Make a change such as:
If you save your notebook and shut down, your changes to the hello function will not be made in the standard_functions.py – you’ll have to copy and paste those back into your standard_functions.py file and perhaps change the function name (hello_change in this example) if you want to keep the orginal. So, the next time you call the standard_functions.py file in your notebook it will look like this:
Obviously this is a super simple example, but I think it is quite powerful and perhaps might help a little with managing the code that, let’s face it, you have made a big effort to write so you might as well re-use it!
There are plenty of other great tips and tricks for using Jupyter Notebooks:
I hope this post is helpful. Let me know email@example.com
image credit https://unsplash.com/photos/3LTht2nxd34
I am a freelancer able to help you with your projects. I offer consultancy, training and writing. I’d be delighted to hear from you.
Feel free to connect or follow me; I am always keen to talk about Earth Observation.