首页 > 解决方案 > networkx 可以从 csv 数据中选择特定列吗?

问题描述

假设我有一个 data.csv 文件,其中包含以下内容:

a 1 2 45
b 2 3 24
c 4 5 98
d 5 6 12

我希望我的节点,我猜,边缘只是第 2 列和第 3 列

所以它输出这样的东西:

在此处输入图像描述

标签: pythonpython-3.xmatplotlibnetworkx

解决方案


使用 pandas 将 .csv 文件作为 df 读取可能是最简单的,然后执行列表推导以将每一行提取为 networkx 库可读的格式。

以下代码部分改编自:Drawing a network with nodes and edges in Python3

...在圆形布局中修改有向图,节点、边和权重是 df 的列

import pandas as pd

import matplotlib.pyplot as plt
import networkx as nx

df = pd.DataFrame({'nodes': [1,2,4,5], 'edges': [2,3,5,6], 'weights': [45,24,98,12]})

# each edge is a tuple of the form (node, edge/node, {'weight': weight})
edges = [(x, y, {'weight': z}) for x, y, z in zip(df['nodes'], df['edges'], df['weights'])]

# a directed graph has arrows pointing to edges
G = nx.DiGraph()

G.add_edges_from(edges)

# create a circular layout
pos = nx.circular_layout(G)

# draw the nodes
nx.draw_networkx_nodes(G,pos, node_size=300)

# draw the labels
nx.draw_networkx_labels(G,pos, font_size=15,font_family='sans-serif')

# draw the edges
nx.draw_networkx_edges(G,pos, edgelist=edges, arrowstyle = '-|>', width=1)

# add weights
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos, edge_labels=labels)
plt.show()

圆形有向图


推荐阅读