valueerror when sorting graph nodes in networkx

I want to sort graph nodes by their different attributes. I have a gdf file that has the nodes and edges of the graph and used networkx to analyze it. But I got an error on sorted fuction. Here is my code (“positive” is one of the node’s attribute that is integer):

G = read_gdf("path/to/gdf file")
sorted_by_attr = sorted(G.nodes, key=lambda n: G.nodes[n]['positive'], reverse=True)

here is the error:

ValueError                                Traceback (most recent call last)
<ipython-input-11-83d54031ff3f> in <cell line: 1>()
----> 1 sorted_by_attr = sorted(G.nodes, key=lambda n: G.nodes[n]['positive'], reverse=True)

/usr/local/lib/python3.10/dist-packages/pandas/core/generic.py in __nonzero__(self)
   1525     @final
   1526     def __nonzero__(self) -> NoReturn:
-> 1527         raise ValueError(
   1528             f"The truth value of a {type(self).__name__} is ambiguous. "
   1529             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any one knows how can I solve this?

Note: This graph has duplicated nodes. May this error be due to this?

  • What type is the attribute positive? Can two of these attributes be compared? It seems like that’s where the problem is coming from.

    – 

  • Its type is integer

    – 

  • The ValueError looks like a numpy error and looks like it is basically telling you that G.nodes[n]['positive'] is not an integer, but a Series.

    – 

  • I tried that but I got another error: TypeError: string indices must be integers

    – 




The way you wrote the key for sorted is wrong.

Imagine I have this list:

seq = [{'positive': 12}, {'positive': 3}, {'positive': 5}]

To sort it, I will write:

result = sorted(seq, key=lambda x: x['positive'])  # good

print(result)
# [{'positive': 3}, {'positive': 5}, {'positive': 12}]

I will not write:

result = sorted(seq, key=lambda n: seq[n]['positive'])  # bad
# TypeError: list indices must be integers or slices, not dict

Leave a Comment