图列表
在这一组练习中,您将使用一个高校消息数据集来学习如何为时间序列分析筛选图。在这个数据集中,节点代表学生,边表示一名学生向另一名学生发送消息。当前的图包含了所有时间点的全部通信。
我们先从只随时间变化边的图开始分析。
该数据集已加载为名为 data 的 DataFrame。您可以在 IPython Shell 中自由探索。尤其是,查看 data['sender'] 和 data['recipient'] 的输出。
本练习是课程的一部分
Python 网络分析中级
练习说明
- 初始化一个名为
Gs的空列表。 - 使用
for循环遍历months。在循环内:- 使用
nx.Graph()函数实例化一个名为G的新的无向图。 - 将所有曾经出现过的节点加入图中。为此,在
G上两次调用.add_nodes_from()方法,第一次以data['sender']为参数,第二次以data['recipient']为参数。 - 将 DataFrame 筛选为仅包含给定月份。此步骤已为您完成。
- 从筛选后的 DataFrame 中添加边。为此,使用
.add_edges_from()方法,并将df_filtered['sender']和df_filtered['recipient']传入zip()。 - 将
G追加到图列表Gs中。
- 使用
交互式实操练习
通过完成这段示例代码来试试这个练习。
import networkx as nx
months = range(4, 11)
# Initialize an empty list: Gs
Gs = []
for month in months:
# Instantiate a new undirected graph: G
G = ____
# Add in all nodes that have ever shown up to the graph
____
____
# Filter the DataFrame so that there's only the given month
df_filtered = data[data['month'] == month]
# Add edges from filtered DataFrame
____
# Append G to the list of graphs
____
print(len(Gs))