2

I had two graphs, g1 and g2. I have applied some rules and mapped them as shown below.

graph:

enter image description here

I would like to convert back the mapped graph to the pandas data frame /table/.

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

Is there any way to do this in Python Pandas?

1 Answer 1

2
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

So, you can convert the nodes of the Graph to a dataframe with make_node_df, and the edges with make_edge_df.

If you want to go from a dataframe to a graph, you can use the inbuilt function nx.from_pandas_edgelist with the edge dataframe, and for the nodes, you can do:

G = nx.Graph()
nodes = node_df_to_ebunch(df, nodename='node')
G.add_nodes_from(nodes)
Sign up to request clarification or add additional context in comments.

8 Comments

I can get the From and To but got error to get the Attribute. KeyError: 'Attribute' .
@Kapital That means the edge attribute is not stored under that name. Can you try to type print(G.edges(data=True)) ? This will give you an idea about which keys are used
I can see it when print(G.node(data=True)) but not print(G.edges(data=True)).
Is there a way to add that attribute to edge information as well?
sure, but this would introduce ambiguity: if both nodes connected by one edge have different attributes, which one would you pick for the edge?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.