Network Analysis with Python



Yüklə 1,5 Mb.
Pdf görüntüsü
səhifə4/12
tarix22.03.2023
ölçüsü1,5 Mb.
#89129
1   2   3   4   5   6   7   8   9   ...   12
l109-tutorial 2015

>>> import math
>>> g.add_node('string')
>>> g.add_node(math.cos) # cosine function
>>> f = open('temp.txt', 'w') # file handle
>>> g.add_node(f)
>>> print g.nodes()
['string',
0x000000000589C5D0>, ]
15


Getting started: adding edges
# Single edge
>>> g.add_edge(1, 2)
>>> e = (2, 3)
>>> g.add_edge(*e) # unpack tuple
# List of edges
>>> g.add_edges_from([(1, 2), (1, 3)])
# A container of edges
>>> g.add_edges_from(h.edges())
# You can also remove any edge
>>> g.remove_edge(1, 2)
16


Getting started: accessing nodes and edges
>>> g.add_edges_from([(1, 2), (1, 3)])
>>> g.add_node('a')
>>> g.number_of_nodes() # also g.order()
4
>>> g.number_of_edges() # also g.size()
2
>>> g.nodes()
['a', 1, 2, 3]
>>> g.edges()
[(1, 2), (1, 3)]
>>> g.neighbors(1)
[2, 3]
>>> g.degree(1)
2
17


Getting started: Python dictionaries
• NetworkX takes advantage of Python dictionaries to store node and edge 
measures. The dict type is a data structure that represents a key-value mapping.
# Keys and values can be of any data type
>>> fruit_dict = {'apple': 1, 'orange': [0.12, 0.02], 42: True}
# Can retrieve the keys and values as Python lists (vector)
>>> fruit_dict.keys()
['orange', 42, 'apple']
# Or (key, value) tuples
>>> fruit_dict.items()
[('orange', [0.12, 0.02]), (42, True), ('apple', 1)]
# This becomes especially useful when you master Python list 
comprehension
18


Getting started: graph attributes
• Any NetworkX graph behaves like a Python dictionary with nodes as primary keys
(for access only!)
• The special edge attribute weight should always be numeric and holds values 
used by algorithms requiring weighted edges.
>>> g.add_node(1, time='10am')
>>> g.node[1]['time']
10am
>>> g.node[1] # Python dictionary
{'time': '10am'}
>>> g.add_edge(1, 2, weight=4.0)
>>> g[1][2]['weight'] = 5.0 # edge already added
>>> g[1][2]
{'weight': 5.0}
19


Getting started: node and edge iterators
• Node iteration
• Edge iteration
>>> g.add_edge(1, 2)
>>> for node in g.nodes(): # or node in g.nodes_iter():
print node, g.degree(node)
1 1
2 1
>>> g.add_edge(1, 3, weight=2.5)
>>> g.add_edge(1, 2, weight=1.5)
>>> for n1, n2, attr in g.edges(data=True): # unpacking
print n1, n2, attr['weight']
1 2 1.5
1 3 2.5
20


Getting started: directed graphs
• Some algorithms work only for undirected graphs and others are not well defined for 
directed graphs. If you want to treat a directed graph as undirected for some measurement 
you should probably convert it using Graph.to_undirected()

Yüklə 1,5 Mb.

Dostları ilə paylaş:
1   2   3   4   5   6   7   8   9   ...   12




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin