Share data between IPython Notebooks

2019-03-12 09:26发布

If I have several IPython notebooks running on the same server. Is there any way to share data between them? For example, importing a variable from another notebook? Thanks!

4条回答
做个烂人
2楼-- · 2019-03-12 09:32

This works for me :

The %store command lets you pass variables between two different notebooks.

data = 'this is the string I want to pass to different notebook' %store data

Now, in a new notebook… %store -r data print(data) this is the string I want to pass to different notebook

I've successfully tested with sklearn dataset :

from sklearn import datasets

dataset = datasets.load_iris()

%store dataset

in notebook to read data :

%store -r dataset

src : https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/

查看更多
干净又极端
3楼-- · 2019-03-12 09:39

IPython supports the %store magic (here is the documentation). It seems to have the same constraints of pickle: if the file can be pickled it will also be storable.

Anyway, it will work for sure with common Python types. Here's a basic example:

var_1 = [1,2,3,4] #list
var_2 = {'a':1,'b':2,'c':3} #dict
var_3 = (6,7,8) #tuple
var_4 = {'d','e','f'} #set
%store var_1
%store var_2
%store var_3
%store var_4
 Stored 'var_1' (list)
 Stored 'var_2' (dict)
 Stored 'var_3' (tuple)
 Stored 'var_4' (set)

Then on a different IPython notebook it will be sufficient to type:

%store -r var_1 
%store -r var_2 
%store -r var_3 
%store -r var_4
查看更多
一夜七次
4楼-- · 2019-03-12 09:42

If your data is in a single variable then have a try at saving it to a file using the %save magic in one notebook and then reading it back in another.

The one difficulty is that the text file will contain the data but no variable definition so I usually contatenate it with a variable definition and then exec the result.

查看更多
劳资没心,怎么记你
5楼-- · 2019-03-12 09:54

I believe that theoretically you should be able to do so with messaging, though I would have to dig a lot deeper to figure it out.

Why would you need this capability though?

查看更多
登录 后发表回答