Search code examples
pandasgraphnetworkxadjacency-matrixedge-list

How to Create a network graph based a simple Datafrme


I am wondering how I can create an Edge list (from, to) based on this type of data. Both columns are inside a pandas data frame and the type is string.

Name Co-Workers
A A,B,C,D
B A,B,C,D
C A,B,C,E
D A,B,D,E
E C,D,E

And also I want to remove connections like AA BB CC ,....


Solution

    • First split the column from string to list of separate values.
    • Second, explode the column.
    • Third, create a directional graph.

    Process the data by mozway code

    And then:

    from matplotlib.pyplot import figure
    G = nx.from_pandas_edgelist(df2, source='Name', target='Co-Workers')
    figure(figsize=(10, 8))
    nx_graph = nx.compose(nx.DiGraph(), G)
    nx.draw_shell(nx_graph, with_labels=True)
    

    Result graph:

    enter image description here