如何从数据框创建网络图

How can I create network graph from dataframe

我有如下 table 这样的数据框:

source destination weight
A B 0.5
A C 0.2
B C 0.1
B D 0.1
C D 0.1

如何按源到目的地创建网络图并显示边上的权重数?

您可以使用 networkx.from_pandas_edgelist 导入数据:

import networkx as nx

G = nx.from_pandas_edgelist(df, source='source', target='destination',
                            edge_attr='weight')

然后您可以按照 example from the documentation 进行修改以考虑权重:

import matplotlib.pyplot as plt

widths = np.array([w for *_, w in G.edges.data('weight')])

pos = nx.spring_layout(G, seed=7)  # positions for all nodes - seed for reproducibi

# nodes
nx.draw_networkx_nodes(G, pos, node_size=700)

# edges
nx.draw_networkx_edges(G, pos, width=widths*10)  # using a 10x scale factor here

# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")

ax = plt.gca()
ax.margins(0.08)
plt.axis("off")
plt.tight_layout()

输出:

import networkx as nx
import pandas as pd

data = {'source':["A", "A", "B", "B", "C"],
        'destination':["B", "C", "C", "D", "D"],
        'weight':[0.5, 0.2, 0.1, 0.1, 0.1]}

df = pd.DataFrame(data)

g = nx.Graph()

weighted_edges = list(zip(*[df[col] for col in df]))

g.add_weighted_edges_from(weighted_edges)