NetworkX系列教程(11)-graph和其他數據格式轉換
阿新 • • 發佈:2018-06-29
sha 小書匠 ans mar http 導入 src 如果 apt
小書匠 Graph 圖論
graph與字典(Dict)示例
graph與列表(List)示例
graph與numpy示例
graph與Scipy示例
graph與Pandas示例
學過線性代數的都了解矩陣,在矩陣上的文章可做的很多,什麽特征矩陣,單位矩陣等.grpah存儲可以使用矩陣,比如graph的鄰接矩陣
,權重矩陣
等,這節主要是在等到graph後,如何快速得到這些信息.詳細官方文檔在這裏
目錄:
- 12.graph和其他數據格式轉換
- 12.1graph與字典(Dict)
- 12.2graph與列表(List)
- 12.3graph與numpy
- 12.4graph與Scipy
- 12.5graph與Pandas
註意:如果代碼出現找不庫,請返回第一個教程,把庫文件導入.
12.graph和其他數據格式轉換
12.1graph與字典(Dict)
- #從字典生成圖
- dod = {0: {1: {‘weight‘: 1}}}
- G = nx.from_dict_of_dicts(dod) #或G=nx.Graph(dpl)
- plt.subplots(1,1,figsize=(6,3))
- nx.draw(G, with_labels=True, font_weight=‘bold‘)
- plt.axis(‘on‘)
- plt.xticks([])
- plt.yticks([])
- plt.show()
- #圖轉換為字典
- print(nx.to_dict_of_dicts(G))
graph與字典(Dict)示例
輸出:
{0: {1: {‘weight‘: 1}}, 1: {0: {‘weight‘: 1}}}
12.2graph與列表(List)
- #從列表中創建graph
- dol = {0: [1,2,3]}
- edgelist = [(0, 1),(0,3),(2,3)]
- G1 = nx.from_dict_of_lists(dol) #或G=nx.Graph(dol)
- G2=nx.from_edgelist(edgelist)
- #顯示graph
- plt.subplots(1,2,figsize=(15,3))
- plt.subplot(121)
- nx.draw(G1, with_labels=True, font_weight=‘bold‘)
- plt.axis(‘on‘)
- plt.xticks([])
- plt.yticks([])
- plt.subplot(122)
- nx.draw(G2, with_labels=True, font_weight=‘bold‘)
- plt.axis(‘on‘)
- plt.xticks([])
- plt.yticks([])
- plt.show()
- #graph轉list
- print(nx.to_dict_of_lists(G1))
- print(nx.to_edgelist(G1))
graph與列表(List)示例
輸出:
{0: [1, 2, 3], 1: [0], 2: [0], 3: [0]}
[(0, 1, {}), (0, 2, {}), (0, 3, {})]
12.3graph與numpy
- #從numpy創建graph
- import numpy as np
- a = np.reshape(np.random.random_integers(0, 1, size=100), (10, 10))
- D = nx.DiGraph(a)
- nx.draw(D, with_labels=True, font_weight=‘bold‘)
- plt.axis(‘on‘)
- plt.xticks([])
- plt.yticks([])
- plt.show()
- #graph返回numpy
- G=nx.Graph()
- G.add_edge(1, 2, weight=7.0, cost=5)
- A1 = nx.to_numpy_matrix(G)
- A2 = nx.to_numpy_recarray(G, dtype=[(‘weight‘, float), (‘cost‘, int)])
- print(A1,A2)
graph與numpy示例
輸出:
- [[0. 7.]
- [7. 0.]] [[(0., 0) (7., 5)]
- [(7., 5) (0., 0)]]
12.4graph與Scipy
- #從scipy創建graph
- G.clear()
- import scipy as sp
- A = sp.sparse.eye(2, 2, 1)
- G = nx.from_scipy_sparse_matrix(A)
- nx.draw(D, with_labels=True, font_weight=‘bold‘)
- plt.axis(‘on‘)
- plt.xticks([])
- plt.yticks([])
- plt.show()
- #graph返回scipy
- A = nx.to_scipy_sparse_matrix(G)
- print(A.todense())
graph與Scipy示例
輸出:
- [[0. 1.]
- [1. 0.]]
12.5graph與Pandas
- #從pandas創建graph
- G.clear()
- import pandas as pd
- df = pd.DataFrame([[1, 1], [2, 1]])
- G = nx.from_pandas_adjacency(df)
- nx.draw(D, with_labels=True, font_weight=‘bold‘)
- plt.axis(‘on‘)
- plt.xticks([])
- plt.yticks([])
- plt.show()
- #graph返回scipy
- df = nx.to_pandas_adjacency(G)
- print(df)
graph與Pandas示例
輸出:
- 0 1
- 0 1.0 2.0
NetworkX系列教程(11)-graph和其他數據格式轉換