In [8]:
#imports
import networkx as nx
G=nx.Graph()

In [9]:
#adding nodes
#one by one
G.add_node(1)

#a list of nodes
G.add_nodes_from([2,3])

#adding nbunch: check documentation
H=nx.path_graph(10)
G.add_nodes_from(H)

In [10]:
#growing edges
#directly
G.add_edge(1,2)

#by definition
e=(2,3)
G.add_edge(*e)

#list of edges
G.add_edges_from([(1,2),(1,3)])

#growing ebunch: check documentation
G.add_edges_from(H.edges())

In [12]:
#remove everything
G.clear()

In [13]:
#interesting additions
G.add_edges_from([(1,2),(1,3)])

G.add_node(1)

G.add_edge(1,2)

G.add_node("spam")

G.add_nodes_from("spam")

In [15]:
#counting nodes
G.number_of_nodes()


Out[15]:
8

In [16]:
#counting edges
G.number_of_edges()


Out[16]:
2

In [17]:
#examining nodes
G.nodes()


Out[17]:
[1, 2, 3, 'spam', 's', 'p', 'a', 'm']

In [18]:
#examining edges
G.edges()


Out[18]:
[(1, 2), (1, 3)]

In [19]:
#examining neighbors
G.neighbors(1)


Out[19]:
[2, 3]

In [20]:
#accessing edges
G.add_edge(1,3)

G[1][3]['color']='blue'

In [22]:
#iterating over edges
FG=nx.Graph()
FG.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
for n,nbrs in FG.adjacency_iter():
    for nbr,eattr in nbrs.items():
        data=eattr['weight']
        if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))


(1, 2, 0.125)
(2, 1, 0.125)
(3, 4, 0.375)
(4, 3, 0.375)

In [23]:
#adding attributes
G = nx.Graph(day="Friday")
G.graph


Out[23]:
{'day': 'Friday'}

In [24]:
#editing graph level attributes
G.graph['day']='Monday'
G.graph


Out[24]:
{'day': 'Monday'}

In [25]:
#adding node attributes
G.add_node(1, time='5pm')
G.add_nodes_from([3], time='2pm')
G.node[1]


Out[25]:
{'time': '5pm'}

In [26]:
G.node[1]['room'] = 714
G.nodes(data=True)


Out[26]:
[(1, {'room': 714, 'time': '5pm'}), (3, {'time': '2pm'})]

In [ ]: