Importing .py files in Google Colab

You can save it first, then import it. from google.colab import files src = list(files.upload().values())[0] open(‘mylib.py’,’wb’).write(src) import mylib Update (nov 2018): Now you can upload easily by click at [>] to open the left pane choose file tab click [upload] and choose your [mylib.py] import mylib Update (oct 2019): If you don’t want to upload … Read more

Automatically import modules when entering the python or ipython interpreter

For ipython, there are two ways to achieve this. Both involve ipython’s configuration directory which is located in ~/.ipython. Create a custom ipython profile. Or you can add a startup file to ~/.ipython/profile_default/startup/ For simplicity, I’d use option 2. All you have to do is place a .py or .ipy file in the ~/.ipython/profile_default/startup directory … Read more

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments): plot([x1, x2], [y1, y2], color=”k”, linestyle=”-“, linewidth=2) (of course you can choose the color, line width, line style, etc.) From your example: import numpy as np import matplotlib.pyplot as plt np.random.seed(5) x = np.arange(1, … Read more

What is %timeit in Python?

%timeit is an IPython magic function, which can be used to time a particular piece of code (a single execution statement, or a single method). From the documentation: %timeit Time execution of a Python statement or expression Usage, in line mode: %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement To use it, for example if … Read more