社交图:Pandas数据帧到Networkx图形

2024-05-20 19:53:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,包含一个用户和他们的每个朋友。格式类似于下面的格式,其中有一个user_id字段和friend_id字段,其中包含每个朋友的对应id。在

user_id | friend_id
   A          B
   A          C
   B          A
   B          G

我的目标是得到一个无向图显示每个用户和每个朋友之间的边缘,他们喜欢下面。在

^{pr2}$

我很难找到如何将pandas链接到networkx或{}以及其他扩展从表格数据创建社交图的资源。在


Tags: 数据用户networkxfriendid目标pandas链接
1条回答
网友
1楼 · 发布于 2024-05-20 19:53:44

作为一个例子,这里是一种使用networkxpandas,和matplotlib来显示无向网络图的方法。在

代码:

import matplotlib.pyplot as plt
import networkx as nx

# store pairs to a list of tuples
tuples = [tuple(x) for x in df.values]

# set up a graph and show it
G = nx.DiGraph()
G.add_edges_from(tuples)
nx.draw_networkx(G)
plt.xticks([], [])
plt.yticks([], [])
plt.show()

输出:

enter image description here

相关问题 更多 >