2014-07-15 106 views
2

我有一個CSV文件,它表示圖形的鄰接矩陣。但是,文件的第一行是節點的標籤,第一列也是節點的標籤。如何將該文件讀入networkx圖形對象?是否有一種完美的pythonic方式來做到這一點沒有黑客入侵?從行和列標題的csv文件中讀取networkx圖形

我至今審判:

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 

甲Tab是分隔符,而不是一個逗號壽。

+0

所以這些標籤是重複在第一行和第一列,所以是多餘的?你可以使用熊貓,它將使用標籤作爲列名,然後生成圖 – EdChum

+0

你也可以發佈一些數據 – EdChum

+0

這是否有幫助? https://stackoverflow.com/questions/15009615/extract-column-from-csv-file-to-use-as-nodelist-in-networkx – Back2Basics

回答

2

你可以將數據讀入一個結構數組。標籤可以從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圖形的類型。例如,

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

使得G一個DiGraph

1

這會工作,不知道這是最好的辦法:

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) 

enter image description here