问题
I am having difficulties in representing a dataframe as a network using networkx. The problem seems to be related to the size of dataframe, or, to better explaining, to the presence of duplicates within the dataframe.
My dataset is
Src Dst
x.serm.cool [x.serm.cool, x.creat.cool]
x.creat.cool [x.creat.cool, x.serm.cool]
sms.sol.tr [sms.sol.tr]
bbb.asl.gt [bbb.asl.gt,cdc.fre.gh,str.alert.jf]
cdc.fre.gh [cdc.fre.gh, bbb.asl.gt,str.alert.jf]
str.alert.jf [str.alert.jf, bbb.asl.gt, cdc.fre.gh]
...
x.serm.cool [x.serm.cool]
where Src's values are used as nodes and Dst as edges. This means that, for example, x.serm.cool has two links, one with itself (but it does not need to consider) and another one with x.creat.cool. Another example: str.alert.jf has three links: one with itself (but it does not has value); one with bbb.asl.gt and another one with cdc.fre.gh. All the links are undirected.
I have tried to represent some nodes in the list using different colours:
df["color"] = "blue"
df.loc[df.Src.isin(["x.serm.cool", "cdc.fre.gh "]), "color"] = "green"
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)
but I have got error message due to: df["Dst"] = df.Dst.apply(lambda x: x[1:-1].split(",")).
As explained by YOBEN_S in a related question (please see at the bottom of this question), the problem is in considering a list instead of string.
However, when I try as follows:
test=["x.serm.cool", "cdc.fre.gh "]
df['color'] = np.where(df.Src.isin(test), "blue", "green")
G = nx.from_pandas_edgelist(df.explode("Dst"), 'Src', 'Dst')
nx.draw(G, node_color = df.color)
I get this error:
ValueError: 'c' argument has 79 elements, which is inconsistent with 'x' and 'y' with size 76.
My original dataset has length 79, while 76 seems to be the length/size of dataset with no Src duplicates. I think that duplicates may be important as they give the node's size, so I would prefer to not remove them from my dataset and network.
Could you please help me to figure this issue out?
Related questions and answers:
- How to split columns in pandas?
- Edgelist from pandas dataframe with nodes of different colours
回答1:
The issue you're facing is because some of the items in your data are duplicated. To solve it, you need to use drop_duplicates in the relevant places:
df["color"] = "blue"
df.loc[df.Src.isin(["x.serm.cool", "cdc.fre.gh"]), "color"] = "green"
df["Dst"] = df.Dst.apply(lambda x: x[1:-1].split(","))
df = df.explode("Dst").drop_duplicates()
G = nx.from_pandas_edgelist(df, 'Src', 'Dst')
colors = df[["Src", "color"]].drop_duplicates()["color"]
nx.draw(G, node_color = colors)
The output:
来源:https://stackoverflow.com/questions/63230886/edgelist-within-pandas-dataframe-to-visualise-using-networkx