Python:如何使用networkx创建一个图,使其与另一个数据框对应?

4
我有两个数据框dfdf1df包含一些节点的信息。
df  Name       Age
0   Jack       33
1   Anna       25
2   Emilie     49
3   Frank      19
4   John       42

df1 包含两个人之间联系次数的信息时,在 df1 中可能会有一些在 df 中不存在的人。

df1    Name1    Name2   c
0      Frank    Paul    2
1      Julia    Anna    5
2      Frank    John    1
3      Emilie   Jack    3
4      Tom      Steven  2
5      Tom      Jack    5

我希望创建一个邻接矩阵,其中节点在df中,连接信息在df1中。
为了从df1创建邻接矩阵,我进行了以下操作:
import networkx as nx
G = nx.Graph()
G = nx.from.pandas_dataframe(df1, 'Name1', 'Name2', ['c'])
adj = nx.adjacency_matrix(G)

然而,这种方式并没有直接对应于df。实际上,我想生成一个6x6的邻接矩阵,其中row 0column 0对应于Jackrow 1column 1对应于Ana,以此类推。

2个回答

2
NetworkX返回的邻接矩阵是稀疏的。首先,将其转换为密集矩阵:
dense = nx.adjacency_matrix(G).todense()

创建一个数据框,其中内容为邻接矩阵,行和列表示所有节点:
adj_df = pd.DataFrame(dense, index=G.nodes(), columns=G.nodes())

最后,根据df定义的数据框,取出其子集:

adj_df.loc[df.Name, df.Name]
#        Jack  Anna  Emilie  Frank  John
#Jack       0     0       1      0     0
#Anna       0     0       0      0     0
#Emilie     1     0       0      0     0
#Frank      0     0       0      0     1
#John       0     0       0      1     0

0

您可以手动添加节点和边来构建有向图:

def from_pandas_dataframe(df, col_from, col_to, col_weight=None, nodes=None):
    """Construct a digraph from dataframe.

    :param df: dataframe contains edge/relation information
    :param col_from: dataframe column name for start of edge
    :param col_to: dataframe column name for end of edge
    :param col_weight: dataframe column name for col_weight, defaults 1 if not provided
    :param nodes: nodes for the graph, default to use nodes from df if not provided
    :return:
    """
    g = nx.OrderedDiGraph()

    # add nodes
    if not nodes:
        nodes = set(df[col_from]) | set(df[col_to])
    g.add_nodes_from(nodes)

    # add edges
    for _, row in df.iterrows():
        from_node, to_node = row[col_from], row[col_to]
        if from_node in nodes and to_node in nodes:
            weight = 1 if not col_weight else row[col_weight]
            g.add_edge(from_node, to_node, weight=weight)

    return g

参数nodes指定图中的节点,不在其中的边和节点将被省略:

g = from_pandas_dataframe(df1, 'Name1', 'Name2', col_weight='c', nodes=df['Name'].tolist())
adj = nx.adjacency_matrix(g)

在样本数据上运行:

>>> print(g.nodes)
['Jack', 'Anna', 'Emilie', 'Frank', 'John']
>>> print(adj)
  (2, 0)    3
  (3, 4)    1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接