Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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:

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?

like image 935
codegurl Avatar asked Jan 30 '26 12:01

codegurl


1 Answers

EDIT: restructured to include explanation for why code fails and how to resolve, following @Joel's suggestion. @Joel's answer provides an explanation of why the code fails, but not a suggestion for how to move resolve it.

Solution

nx.read_weighted_edgelist will ignore input lines that start with #, so if you change the first line of your csv file from

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.

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

Why your code failed

(this is incorporated from the answer of @Joel)

When it encounters the first line (from your comments: 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.

It is difficult to convert the string c_weight to a float. So it gives an error.

like image 57
Bonlenfum Avatar answered Feb 02 '26 02:02

Bonlenfum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!