Python 具有不同颜色节点的pandas数据框中的Edgelist
我有以下数据框:Python 具有不同颜色节点的pandas数据框中的Edgelist,python,pandas,networkx,Python,Pandas,Networkx,我有以下数据框: Src Dst A [A,B] B [B,A] C [C] D [D,E,F] E [E,D,F] F [F,D,E] ... 我想生成一个网络,其中,Src是节点,Dst是边,新列,Weight可以为节点分配不同的颜色(绿色),即a或D,而其他节点都是相同的(例如蓝色) 我尝试了以下方法: 创建新的列权重 这里的问题是我不知道如何分配颜色,所以我只尝试为a或D分配值1,为所有其他值分配值0,并分别更改颜色 对于图表,我使用了以下内容 G
Src Dst
A [A,B]
B [B,A]
C [C]
D [D,E,F]
E [E,D,F]
F [F,D,E]
...
我想生成一个网络,其中,Src
是节点,Dst
是边,新列,Weight
可以为节点分配不同的颜色(绿色),即a
或D,而其他节点都是相同的(例如蓝色)
我尝试了以下方法:
创建新的列权重
这里的问题是我不知道如何分配颜色,所以我只尝试为a或D分配值1,为所有其他值分配值0,并分别更改颜色
对于图表,我使用了以下内容
G = nx.from_pandas_edgelist(df, 'Src', 'Dst')
上面的代码行与Dst中的节点行没有连接,我无法理解原因。我发现了一些可能有助于分配颜色的方法:
colors=[]
for n in df.Src:
if n in df.Weight:
colors.append('g')
else:
colors.append('b')
# nodes
nx.draw_networkx_nodes(G,pos, node_color = colors)
但我有一个错误:
ValueError:“c”参数有79个元素,这与
尺寸为76的“x”和“y”
下面的图像与我的预期输出类似(A
和D
节点绿色,其他蓝色,以及基于Dst
数据的链接;请注意,下面的图像当前既没有再现预期的颜色,也没有再现预期的边缘)
你能帮我给我一些建议吗?这里有一个方法:
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)
输出为:
你好,2012年。我提出了一个新问题,如果你想看一看(与此相关):。再次感谢你的帮助。我来看看。这是给我这个错误的数据集:
data=['a'、['a'、'B']]、['B'、['B'、'a']]、['C'、['C']]、['D'、['D'、'E'、'F']]、['E'、['E'、['E'、'D'、'F']]、['F'、['F'、['F'、['F'、'F'、'D'、'E']]]、['F']、['F']、['F']、['F']、['F'];创建熊猫df pd.DataFrame=pd.DataFrame(数据、数据框、['D'、'Src'、'Src']),请参见我的最新代码编辑)。我现在也来看看另一个问题。您好@Roy2012,我就一个类似的问题提出了一个新问题,以防您想看一看:我还没有找到解决方案
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)