Store networkx graph object
Question:
I have a huge graph with about 5000 nodes that I made it with networkX. It takes about 30 seconds to create this graph each time I execute my script. After this relatively long time I can run my analysis like shortest_path
and so on.
My question is, is there any way to store the object of this graph in file or something like this and each time I run my script, networkX read that file and load all of my graph?
Answers:
You could use gpickle
to do this. Assuming your graph is denoted with G
, you could save it by:
nx.write_gpickle(G,'myGraph.gpickle')
and load it with
G = nx.read_gpickle('myGraph.gpickle')
https://networkx.org/documentation/stable//reference/readwrite/gpickle.html#pickled-graphs
As of version 2.6, methods write_gpickle
and read_gpickle
are deprecated. Try this instead:
import pickle
# save graph object to file
pickle.dump(G, open('filename.pickle', 'wb'))
# load graph object from file
G = pickle.load(open('filename.pickle', 'rb'))
Note the options 'wb'
to dump and 'rb'
to load in open()
.
I have a huge graph with about 5000 nodes that I made it with networkX. It takes about 30 seconds to create this graph each time I execute my script. After this relatively long time I can run my analysis like shortest_path
and so on.
My question is, is there any way to store the object of this graph in file or something like this and each time I run my script, networkX read that file and load all of my graph?
You could use gpickle
to do this. Assuming your graph is denoted with G
, you could save it by:
nx.write_gpickle(G,'myGraph.gpickle')
and load it with
G = nx.read_gpickle('myGraph.gpickle')
https://networkx.org/documentation/stable//reference/readwrite/gpickle.html#pickled-graphs
As of version 2.6, methods write_gpickle
and read_gpickle
are deprecated. Try this instead:
import pickle
# save graph object to file
pickle.dump(G, open('filename.pickle', 'wb'))
# load graph object from file
G = pickle.load(open('filename.pickle', 'rb'))
Note the options 'wb'
to dump and 'rb'
to load in open()
.