開始使用免費開始

建立 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())
編輯並執行程式碼