【问题标题】:Creating NetworkX graph from a dataframe从数据框创建 NetworkX 图
【发布时间】:2020-06-23 19:42:45
【问题描述】:

我正在尝试构建一个网络,其中节点是人名,并且在关系索引大于0.60 的节点/人之间创建边。

数据来自熊猫

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

我所做的是得到表格的线性表示:

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 相互连接而其他人断开连接的图表。

【问题讨论】:

  • 我不确定我是否完全理解。在您分享的数据中,Mark 的关系指数为 0.85。但是谁呢?
  • 嗨扭曲。所有关系索引大于0.6的节点都相互有关系(问题比较复杂,这只是一个简化版;)

标签: python pandas networkx


【解决方案1】:

您的代码中有什么问题:

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)

【讨论】:

  • 谢谢@warped。我收到此错误:AttributeError: module 'matplotlib.cbook' has no attribute 'is_numlike'。您认为是由于某些包裹造成的吗?
  • @Math This post 表示该错误是由于 matplotlib 以两种不同的方式安装造成的。因此,这应该与 networkx 无关,而与绘制图形的代码无关。
猜你喜欢
  • 1970-01-01
  • 2023-02-10
  • 2019-04-22
  • 2016-05-17
  • 1970-01-01
  • 2021-01-09
  • 2018-12-15
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多