我有一个由“用户”和“用户之间的交互”组成的数据集(pandas框架),例如:
user, interactions
1, 2 7 9 4
2, 7 1 5 7 8 3
4, 9 5 3每个数字对应一个用户的ID。每个用户可以有N个交互,其中N个>=为0。
逗号后面的值是用户的邻居。
如何从这些数据中以一种执行的方式创建一个networkx图?
我在拆分字符串后尝试了一些循环,但性能非常差。
谢谢!
发布于 2018-01-12 03:38:15
Networkx具有从边列表(.add_edges_from())中添加边的功能。
import networkx as nx
import matplotlib.pyplot as plt
user = [1,2,4]
interactions = [
[2, 7, 9, 4],
[7, 1, 5, 7, 8, 3],
[9, 5, 3]
]
# create the edge list
elist = []
for v1,v2 in zip(user,interactions):
elist.extend([(v1,v) for v in v2])
# create graph from edge list
G = nx.Graph()
G.add_edges_from(elist)
# plot graph
nx.draw(G, with_labels=True)
plt.show()

https://stackoverflow.com/questions/48203528
复制相似问题