简体   繁体   English

使用networkx加权边缘列表时出错

[英]Error using networkx weighted edgelist

I have created a weighted edge list that I am trying to use to generate a weighted undirected graph: 我创建了一个加权边缘列表,我试图用它来生成加权无向图:

The data is in a csv which looks like the following in excel: 数据在csv中,在excel中如下所示:

node1 node2 weight

a     b     0.1

a     c     0.3

As recommended by other StackOverflow posts, I have been using the following code to read in the csv: 正如其他StackOverflow帖子所推荐的那样,我一直在使用以下代码来读取csv:

fh=open("<file_location>.csv", 'r')
G = nx.read_weighted_edgelist(fh,delimiter=',')

The first line runs fine but the second yields the error message: 第一行运行正常,但第二行产生错误消息:

TypeError: Failed to convert weight data weight to type type 'float'

If I check G, it has read in the nodes fine but not the weights, any ideas? 如果我检查G,它已经在节点中读取了很好但没有权重,任何想法?

EDIT: restructured to include explanation for why code fails and how to resolve, following @Joel's suggestion. 编辑:根据@ Joel的建议重组,包括解释代码失败的原因以及如何解决。 @Joel's answer provides an explanation of why the code fails, but not a suggestion for how to move resolve it. @ Joel的回答解释了代码失败的原因,但没有提出如何解决问题的建议。

Solution

nx.read_weighted_edgelist will ignore input lines that start with # , so if you change the first line of your csv file from nx.read_weighted_edgelist将忽略以#开头的输入行,因此如果您更改csv文件的第一行

node1 node2 weight

to

#node1 node2 weight

then you should be able to read in the network with weights. 那么你应该能够在网络中读取权重。

Also note that read_weighted_edgelist accepts a file path (string) as well as a file handle, so if you aren't using fh again, you don't need to open it first, just pass it directly. 另请注意, read_weighted_edgelist接受文件路径(字符串)和文件句柄,因此如果您不再使用fh ,则无需先打开它,只需直接传递即可。

G = nx.read_weighted_edgelist("<file_location>.csv", delimiter=',')

Why your code failed 你的代码失败的原因

(this is incorporated from the answer of @Joel) (这是@Joel的回答)

When it encounters the first line (from your comments: a_node1,b_node2,c_weight ) 遇到第一行时(来自你的评论: a_node1,b_node2,c_weight

it interprets the first node to be a_node1 , the second to be b_node2 , and it tries to assign the weight c_weight to the edge between them. 它将第一个节点解释为a_node1 ,第二个节点为b_node2 ,并尝试将权重c_weight分配给它们之间的边缘。

It is difficult to convert the string c_weight to a float. 将字符串c_weight转换为float很困难。 So it gives an error. 所以它给出了一个错误。

When it encounters the first line (from your comments: a_node1,b_node2,c_weight ) 遇到第一行时(来自你的评论: a_node1,b_node2,c_weight

it interprets the first node to be a_node1 , the second to be b_node2 , and it tries to assign the weight c_weight to the edge between them. 它将第一个节点解释为a_node1 ,第二个节点为b_node2 ,并尝试将权重c_weight分配给它们之间的边缘。

It is difficult to convert the string c_weight to a float. 将字符串c_weight转换为float很困难。 So it gives an error. 所以它给出了一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM