winawer
winawer

Reputation: 173

Create networkx graph from pandas df with column entries as tuples of neighbours

I have a Pandas dataframe such that the first column of every entry has the name of a node, and the second column is a tuple of the neighbours of that node. How can I construct a networkx graph directly from this dataframe.

import networkx as nx
import pandas as pd
data = [[1,(2,4)],[2, (1,3)], [3, (1,2,3)], [4, (1)]]
exdf = pd.DataFrame(data, columns = ["A","B"])
G = nx.from_pandas_edgelist(exdf, "A", "B")
        

The last line of code builds a graph with edges connecting every entry of the columns "A" and "B". However, this doesn't seem to work if the column entries are a list or tuple of nodes rather than a single node. Is there an easy fix for this?

Upvotes: 1

Views: 293

Answers (1)

RJ Adriaansen
RJ Adriaansen

Reputation: 9619

What you're passing to networkx is not yet an edgelist. You can explode column B to create one:

exdf = exdf.explode('B')

Upvotes: 2

Related Questions