Edgelist from pandas dataframe with nodes of different colours

前端 未结 1 1068
情书的邮戳
情书的邮戳 2021-01-28 02:30

I have the following data frame:

Src  Dst
A    [A,B]
B    [B,A]
C    [C]
D    [D,E,F]
E    [E,D,F]
F    [F,D,E]
...

I would like to generate a ne

相关标签:
1条回答
  • 2021-01-28 03:02

    Here's a way to do that:

    df["color"] = "blue"
    df.loc[df.Src.isin(["A", "D"]), "color"] = "green"
    
    # The following line is needed because, at least in the way my dataset 
    # is created, 'Dst' is not a list but rather a string. 
    # For example, Dst of 'A' is the string "[A,B]". Here, 
    # I'm converting it to the list ["A", "B"]
    # If your data doesn't need this, just comment this line out. 
    df["Dst"] = df.Dst.apply(lambda x: x[1:-1].split(","))
    
    G = nx.from_pandas_edgelist(df.explode("Dst"), 'Src', 'Dst')
    nx.draw(G, node_color = df.color)
    

    The output is:

    0 讨论(0)
提交回复
热议问题