【问题标题】:Reading a networkx graph from a csv file with row and column header从带有行和列标题的 csv 文件中读取 networkx 图
【发布时间】:2014-09-05 12:20:36
【问题描述】:

我有一个表示图的邻接矩阵的 CSV 文件。然而,该文件的第一行是节点的标签,第一列也是节点的标签。如何将此文件读入networkx 图形对象?有没有一种简洁的pythonic方法可以做到这一点而无需四处乱窜?

到目前为止我的试验:

x = np.loadtxt('file.mtx', delimiter='\t', dtype=np.str)
row_headers = x[0,:]
col_headers = x[:,0]
A = x[1:, 1:]
A = np.array(A, dtype='int')

但这当然不能解决问题,因为我需要在图表创建中为节点添加标签。

数据示例:

Attribute,A,B,C
A,0,1,1
B,1,0,0
C,1,0,0

制表符是分隔符,而不是逗号。

【问题讨论】:

  • 所以这些标签在第一行和第一列是重复的,所以是多余的?您可以只使用将标签用作列名的熊猫,然后构建图表
  • 你能不能也发一些数据

标签: python csv networkx


【解决方案1】:

您可以将数据读入结构化数组。可以从x.dtype.names获取标签,然后使用nx.from_numpy_matrix生成networkx图:

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

# read the first line to determine the number of columns
with open('file.mtx', 'rb') as f:
    ncols = len(next(f).split('\t'))

x = np.genfromtxt('file.mtx', delimiter='\t', dtype=None, names=True,
                  usecols=range(1,ncols) # skip the first column
                  )
labels = x.dtype.names

# y is a view of x, so it will not require much additional memory
y = x.view(dtype=('int', len(x.dtype)))

G = nx.from_numpy_matrix(y)
G = nx.relabel_nodes(G, dict(zip(range(ncols-1), labels)))

print(G.edges(data=True))
# [('A', 'C', {'weight': 1}), ('A', 'B', {'weight': 1})]

nx.from_numpy_matrix 有一个 create_using 参数,您可以使用它来指定您希望创建的 networkx Graph 的类型。例如,

G = nx.from_numpy_matrix(y, create_using=nx.DiGraph())

使G 成为DiGraph

【讨论】:

    【解决方案2】:

    这可行,但不确定这是最好的方法:

    In [23]:
    
    import pandas as pd
    import io
    import networkx as nx
    temp = """Attribute,A,B,C
    A,0,1,1
    B,1,0,0
    C,1,0,0"""
    # for your case just load the csv like you would do, use sep='\t'
    df = pd.read_csv(io.StringIO(temp))
    df
    Out[23]:
      Attribute  A  B  C
    0         A  0  1  1
    1         B  1  0  0
    2         C  1  0  0
    
    In [39]:
    
    G = nx.DiGraph()
    for col in df:
        for x in list(df.loc[df[col] == 1,'Attribute']):
            G.add_edge(col,x)
    
    G.edges()
    Out[39]:
    [('C', 'A'), ('B', 'A'), ('A', 'C'), ('A', 'B')]
    
    In [40]:
    
    nx.draw(G)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多