python - networkx 可以从 csv 数据中选择特定列吗?
问题描述
假设我有一个 data.csv 文件,其中包含以下内容:
a 1 2 45
b 2 3 24
c 4 5 98
d 5 6 12
我希望我的节点,我猜,边缘只是第 2 列和第 3 列
所以它输出这样的东西:
解决方案
使用 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()
推荐阅读
- node.js - 如何使用名称启动项目 node.js 错误
- java - 启用 Javascript HttpClient
- javascript - 如果我只使用一个操作符,我应该使用管道操作符吗?
- c - C实践中与二维字符数组有关的逻辑
- typescript - 无法在 TypeScript 中使用可选参数创建动态类型
- macos - 终端 unix 命令发现设置模式的问题(愚蠢的问题)
- spring-integration - 尝试处理某些 RSS 提要时,Spring Integration 过早结束文件异常
- node.js - 让 node.js 应用程序从 AWS S3 存储桶中提取多个页面时遇到问题(超过 1000 个文件)
- python - OpenCV 找不到网络摄像头,但 Cheese 可以
- swift - 展开和折叠 1 个 Tableview 部分,1 行