Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Networkx KeyError: 'source' with from_pandas_edgelist for undirected edgelist

I have an edgelist in a pandas dataframe that looks like this:

    topic   neighbor
0   K       Kl
1   K       Pr
2   Kl      TS
3   Pr      Kl
4   Pr      Pr

When I turn this into a Graph (using networkx as nx) with G = nx.from_pandas_edgelist(df) it gives me KeyError: ‘source’.

It works when I specify a source and target G = nx.from_pandas_edgelist(df, "topic", "neighbor") but this is an undirected Graph so I do not really want a source and target.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this the way it has to be done? Will specifying a source and target have implications for later calculations of degree_centrality?

>Solution :

Yes, creating an undirected network from a dataframe requires specifying source and target.

It’s not necessary, but to be sure that the graph is undirected, one can specify create_using kwarg:

from networkx import Graph, from_pandas_edgelist

df = ...

# note that Graph is the default setting, so specifying
# create_using=Graph is optional
G = from_pandas_edgelist(df, "topic", "neighbor", create_using=Graph)


print(G.is_directed())
# False
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading