建立 nodelist
現在你要練習把圖形轉換成 pandas 的表示法。若你上過 DataCamp 的 pandas 課程,就會知道有個 DataFrame.to_csv('filename.csv') 方法,可以把結果存成 CSV 檔,方便人類閱讀。這裡主要想讓你掌握的概念,是把圖形轉換成「紀錄清單」的流程。
先在 IPython Shell 中呼叫 list(G.nodes(data=True))[0],重新熟悉圖形資料結構,並檢視圖中的一個節點。
本練習屬於課程
Python 網路分析進階
練習說明
- 建立一個名為
nodelist的空節點清單。 - 使用
for迴圈走訪G_people的各個節點。在迴圈內:- 使用
.update()方法並以d作為引數,更新nodeinfo字典。 - 將
nodeinfo字典附加到nodelist。
- 使用
- 使用
pd.DataFrame()函式,將 nodelist 建立成名為node_df的 pandas DataFrame。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize a list to store each edge as a record: nodelist
nodelist = ____
for n, d in G_people.nodes(data=True):
# nodeinfo stores one "record" of data as a dict
nodeinfo = {'person': n}
# Update the nodeinfo dictionary
____
# Append the nodeinfo to the node list
____
# Create a pandas DataFrame of the nodelist: node_df
node_df = ____
print(node_df.head())