pandas数据框内的Edgelist使用networkx进行可视化

2024-10-02 00:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用networkx将数据帧表示为网络时遇到困难。问题似乎与数据帧的大小有关,或者,为了更好地解释,与数据帧中是否存在重复项有关

我的数据集是

   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]

其中Src的值用作节点Dst用作边。这意味着,例如,x.serm.cool有两个链接,一个链接自身(但不需要考虑),另一个链接x.creat.cool。另一个例子:str.alert.jf有三个链接:一个链接本身(但它没有价值);一个带bbb.asl.gt,另一个带dc.fre.gh。所有链接都是无方向的。 我尝试使用不同的颜色表示列表中的一些节点:

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) 

但我收到了错误消息,原因是:df["Dst"] = df.Dst.apply(lambda x: x[1:-1].split(","))。 正如YOBEN_S在一个相关问题中所解释的(请参见问题底部),问题在于考虑列表而不是字符串。 然而,当我尝试以下方法时:

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)

我得到这个错误:

ValueError: 'c' argument has 79 elements, which is inconsistent with 'x' and 'y' with size 76.

我的原始数据集的长度为79,而76似乎是没有Src重复项的数据集的长度/大小。我认为副本可能很重要,因为它们给出了节点的大小,所以我不希望将它们从我的数据集和网络中删除

你能帮我解决这个问题吗

相关问题和答案:


Tags: 数据gtsrcdf链接ghcolordst
1条回答
网友
1楼 · 发布于 2024-10-02 00:26:14

您面临的问题是因为数据中的某些项是重复的。要解决此问题,您需要在相关位置使用drop_duplicates

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)

输出:

enter image description here

相关问题 更多 >

    热门问题