簡體   English   中英

pandas dataframe 中的邊緣列表以使用 networkx 進行可視化

[英]Edgelist within pandas dataframe to visualise using networkx

我在使用 networkx 將 dataframe 表示為網絡時遇到了困難。 該問題似乎與 dataframe 的大小有關,或者為了更好地解釋,與 dataframe 中存在重復項有關。

我的數據集是

   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另一個帶有 c 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重復的數據集的長度/大小。 我認為重復項可能很重要,因為它們給出了節點的大小,所以我不想將它們從我的數據集和網絡中刪除。

你能幫我解決這個問題嗎?

相關問題和答案:

您面臨的問題是因為您的數據中的某些項目是重復的。 要解決它,您需要在相關地方使用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)

output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM