【问题标题】:Can networkx select specific columns from csv data?networkx 可以从 csv 数据中选择特定列吗?
【发布时间】:2020-04-06 03:53:15
【问题描述】:

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

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

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

所以它会输出如下内容:

【问题讨论】:

  • 你有什么问题?
  • 我正在尝试仅使用 data.csv 文件中的第 2 列和第 3 列来输出类似于图像中的内容,我只是想知道 networkx 是否有办法做到这一点,因为 read_edgelist() 不接受我当前的文件

标签: python python-3.x matplotlib networkx


【解决方案1】:

使用 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()

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2020-03-20
    相关资源
    最近更新 更多