python - 将 Networkx 图转换为具有其属性的数据框

标签 python pandas networkx

我有两个图,g1 和 g2。我应用了一些规则并映射它们,如下所示。

图表:

enter image description here

我想将映射图转换回 pandas 数据框/table/。

From        Attribute        To         
10/10       Start          130/21
130/21      Left           190/190
190/190     Right          240/204
240/204     End             -

有什么方法可以在Python Pandas 中做到这一点吗?

最佳答案

def make_node_df(G):
    nodes = {}
    for node, attribute in G.nodes(data=True):
        if not nodes.get('node'):
            nodes['node'] = [node]
        else:
            nodes['node'].append(node)

        for key, value in attribute.items():
            if not nodes.get(key):
                nodes[key] = [value]
            else:
                nodes[key].append(value)

    return pd.DataFrame(nodes)

def make_edge_df(G):
    edges = {}
    for source, target, attribute in G.edges(data=True):

        if not edges.get('source'):
            edges['source'] = [source]
        else:
            edges['source'].append(source)

        if not edges.get('target'):
            edges['target'] = [target]
        else:
            edges['target'].append(target)

        for key, value in attribute.items():
            if not edges.get(key):
                edges[key] = [value]
            else:
                edges[key].append(value)
    return pd.DataFrame(edges)


def node_df_to_ebunch(df, nodename='node'):

    attributes = [col for col in df.columns if not col==nodename]

    ebunch = []

    for ix, row in df.iterrows():
        ebunch.append((row[nodename], {attribute:row[attribute] for attribute in attributes}))

    return ebunch

因此,您可以使用 make_node_df 将图的节点转换为数据帧,并使用 make_edge_df 将边转换为数据帧。

如果您想从数据帧转换为图形,可以将内置函数 nx.from_pandas_edgelist 与边缘数据帧一起使用,对于节点,您可以执行以下操作:

G = nx.Graph()
nodes = node_df_to_ebunch(df, nodename='node')
G.add_nodes_from(nodes)

关于python - 将 Networkx 图转换为具有其属性的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62383699/

相关文章:

python - NetworkX vs Scipy 所有最短路径算法

python - 如何在 Django 中创建 'notify me of followup comments via e-mail' 按钮?

python - 如何在 pandas dataframe python 上使用 apply 函数时中断?

python - 如何在 Python 中从文件系统中随机采样文件

python - 通过切片重命名 Pandas 列,导致合并失败

python - 将 Pandas 数据框转换为 float

python - 如何设置 NetworkX 边缘标签偏移量? (避免标签重叠)

networkx - 删除边缘属性的Pythonic方法

python - vscode 无法使用函数 "go to definition"并且无法在问题中打开文件

python - 使用 Postman 进行 Django Rest Framework token 身份验证