📜  networkx add edge (1)

📅  最后修改于: 2023-12-03 15:17:51.489000             🧑  作者: Mango

NetworkX Add Edge

Introduction

NetworkX is a Python library used for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It provides tools to represent and analyze networks, including adding and removing edges or nodes.

This guide will focus specifically on the add_edge function in NetworkX, which allows programmers to add edges between two nodes in a graph.

Syntax

The general syntax for add_edge function is as follows:

add_edge(G, u, v, **attr)
  • G: The graph in which the edge will be added.
  • u: The source node for the new edge.
  • v: The target node for the new edge.
  • attr (optional): Additional attributes for the edge.
Example

Let's start by creating an empty graph and adding a few nodes:

import networkx as nx

G = nx.Graph()
G.add_node('Node 1')
G.add_node('Node 2')
G.add_node('Node 3')

Now, we can add an edge between two nodes using the add_edge function:

G.add_edge('Node 1', 'Node 2')

By default, this function will create an undirected edge. If you want to create a directed edge instead, you need to specify the create_using parameter as a DiGraph (directed graph) object:

G = nx.DiGraph()
G.add_node('Node 1')
G.add_node('Node 2')
G.add_edge('Node 1', 'Node 2')
Attributes

You can also assign additional attributes to the newly created edge. For example, let's add a weight of 2 to the edge between Node 1 and Node 2:

G.add_edge('Node 1', 'Node 2', weight=2)

You can later access these attributes using the G.edge attribute. For instance, to retrieve the weight of the edge between Node 1 and Node 2, you can use:

G.edge['Node 1']['Node 2']['weight']
Conclusion

The add_edge function in NetworkX provides a simple way to add edges between nodes in a graph. By specifying the source node, target node, and optional attributes, you can create both undirected and directed edges with ease.