开始使用免费开始使用

构建边列表

现在,您将把相同的思路应用到构建边列表上。来试一试吧!

与上一个练习类似,请先在 IPython Shell 中运行 list(G.edges(data=True))[0],以便在继续之前了解边列表这一数据结构。

本练习是课程的一部分

Python 网络分析中级

查看课程

练习说明

  • 初始化一个名为 edgelist 的列表,用于将每条边存储为一条记录。
  • 使用 for 循环遍历 G_people 的各条边。在循环内部:
    • 初始化一个名为 edgeinfo 的字典,存放边的信息。
    • 使用元数据字典 d 来更新 edgeinfo 字典。
    • edgeinfo 字典追加到 edgelist
  • 基于该边列表创建一个名为 edge_df 的 pandas DataFrame。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Initialize a list to store each edge as a record: edgelist
edgelist = []
for n1, n2, d in G_people.edges(data=True):
    # Initialize a dictionary that shows edge information: edgeinfo
    edgeinfo = {'node1':____, 'node2':____}
    
    # Update the edgeinfo data with the edge metadata
    ____
    
    # Append the edgeinfo to the edgelist
    ____
    
# Create a pandas DataFrame of the edgelist: edge_df
edge_df = ____
print(edge_df.head())
编辑并运行代码