Pandas 到二分图

Pandas to bipartite graph

我已经在我的图中添加了节点,但我似乎无法理解向其添加边的方法。边对应于我的数据透视表中的任何值 1。 table 的形式如下:

movie_id  1     2     3     4     5     ...  500
user_id                                 ...                              
501       1.0   0.0   1.0   0.0   0.0  ...   0.0  
502       1.0   0.0   0.0   0.0   0.0  ...   0.0   
503       0.0   0.0   0.0   0.0   0.0  ...   1.0   
504       0.0   0.0   0.0   1.0   0.0  ...   0.0  
.         ...
.

1200

这是我用于节点的代码:

B = nx.Graph()
B.add_nodes_from(user_rating_pivoted.index, bipartite=0)
B.add_nodes_from(user_rating_pivoted.columns, bipartite=1)

而且我想应该以类似的方式形成边缘:

add_edges_from(...) for idx, row in user_rating_pivoted.iterrows())

让我们为这些索引和列添加前缀,并使用它们作为节点以更容易地关联连接:

print(df)

          movie_1  movie_2  movie_3  movie_4  movie_5  movie_6
user_1      1.0      1.0      1.0      1.0      0.0      0.0
user_2      1.0      0.0      0.0      0.0      0.0      0.0
user_3      0.0      1.0      0.0      0.0      0.0      1.0
user_4      1.0      0.0      1.0      0.0      1.0      0.0

为了获得边(并保留节点名称),我们可以使用pandas来稍微转换数据帧。我们可以使用 stack 得到一个 MultiIndex,然后索引 1 的值。然后我们可以使用 add_edges_from 添加所有 edge 数据:

B = nx.Graph()
B.add_nodes_from(df.index, bipartite=0)
B.add_nodes_from(df.columns, bipartite=1)

s = df.stack()
B.add_edges_from(s[s==1].index)

我们可以使用 bipartite_layout 对二分图进行漂亮的布局:

top = nx.bipartite.sets(B)[0]
pos = nx.bipartite_layout(B, top)

nx.draw(B, pos=pos, 
        node_color='lightgreen', 
        node_size=2500,
        with_labels=True)

请注意,尽管这些高度稀疏的矩阵很可能会导致图形断开连接,即并非所有节点都连接到某个其他节点的图形,并且尝试获取这两个集合将引发指定的错误 here.

AmbiguousSolution – Raised if the input bipartite graph is disconnected and no container with all nodes in one bipartite set is provided. When determining the nodes in each bipartite set more than one valid solution is possible if the input graph is disconnected.

在这种情况下,您可以将其绘制为常规图形:

rcParams['figure.figsize'] = 10 ,8
nx.draw(B, 
        node_color='lightgreen', 
        node_size=2000,
        with_labels=True)