從 pandas DataFrame 建立圖形
先從 pandas DataFrame 建立圖形開始。這個練習中,你會透過迴圈走訪邊列表(這是一個 DataFrame 物件),來建立一個新的二分圖。
為了簡化,在此圖形建構流程中,學生與論壇節點之間的任何邊,都視為該學生在整個資料集時間範圍內貼到該論壇的「最後一條」邊;當然也有其他作法可以避免這個簡化。
此外,為了縮短練習的執行時間,我們提供了一個次抽樣過的邊列表作為 data。請在 IPython Shell 中探索它,先熟悉一下內容。
本練習屬於課程
Python 網路分析進階
練習說明
- 建立一個名為
G的新 Graph。 - 從每個分區加入節點。使用
.add_nodes_from()方法來完成。兩個分區是 「'student'」 與 「'forum'」。例如,要從 「'student'」 分區加入節點,.add_nodes_from()的參數應為data['student']與bipartite='student'。 - 加入每條邊,並附上該邊建立的日期。請在迴圈中使用
.add_edge()方法,參數為d['student']、d['forum'],以及date=d['date']。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
import networkx as nx
# Instantiate a new Graph: G
G = ____
# Add nodes from each of the partitions
____
____
# Add in each edge along with the date the edge was created
for r, d in data.iterrows():
____