Gareth Netto
Gareth Netto

Reputation: 105

Google Colab source function in other Colab notebook

I have an ipynb on Google Colab my_functions.ipynb which consists of a simple function.

def get_mean(dat, col_nm):
  return dat[col_nm].mean()

From a different python notebook other_notebook.ipynb on Google Colab I'd like to source this function so that I could use it however I haven't been able to see a solution anywhere.

Appreciate any help on this.

Thanks,

Gareth

Upvotes: 6

Views: 3964

Answers (2)

Lex Podgorny
Lex Podgorny

Reputation: 2930

Simple.

from google.colab import drive
drive.mount('/content/gdrive')

then

libdir = "/content/gdrive/My\ Drive/Colab\ Notebooks/lib/"
%run {libdir}my_functions.ipynb

Now, all you've defined in my_functions.ipynb becomes available in the scope of your current notebook. Same thing you can do with regular .py files as well.

Upvotes: 0

Job Brüggen
Job Brüggen

Reputation: 303

I saved my file with some useful functions as a .py file.

Then I store in Google Drive as 'functions.py'.

I then load my functions with the following call:

%run '/content/drive/My Drive/Colab Notebooks/functions.py'

Upvotes: 3

Related Questions