从数据框创建 NetworkX 图

Creating NetworkX graph from a dataframe

我正在尝试构建一个网络,其中节点是人名,边是在关系指数大于 0.60 的 nodes/people 之间创建的。

数据来自pandas

Name      Relationship index
Julie        0.4
Marie        0.2
Bob          0.7 
Mark         0.85
Chris        0.43

我所做的是得到 table:

的线性表示
dat = df.set_index('Name').stack()

然后尝试在 relationship index > 0.6:

的人之间建立联系
dat = dat[dat['Relationship index']>0.6]

并获取边缘列表:

edges = dat.index.tolist()

然后我一直在将网络构建为二分图:

G = nx.Graph(edges)
Gp = nx.bipartite.project(G, dat.set_index('Name').columns)

Gp.edges()

不幸的是我收到了这个错误:

----> 2 dat = dat[dat['Relationship index']>0.6]

AttributeError: 'Series' object has no attribute 'Relationship index'

你能告诉我哪里出了问题吗?

预期输出:

Bob 和 Mark 相互连接而其他人断开连接的图表。

您的代码中有什么问题:

dat = df.set_index('Name').stack()
this line gets rid of column names, 
so you cannot access them with ['Relationship index']
anymore

对于您的具体问题,您可以使用 itertools:

import itertools

matches = df[df['Relationship index']>.6]['Name'].tolist()
edges = itertools.product(matches, matches)

G = nx.Graph()
G.add_nodes_from(df['Name'])
G.add_edges_from(edges)

nx.draw_networkx(G)