How to preserve, or at least sort edge attributes when creating a graph from a shapefile in networkx?

StackOverflow https://stackoverflow.com/questions/23330792

  •  10-07-2023
  •  | 
  •  

Question

I've made a graph in networkx from a shapefile using :

import networkx as nx
layer = nx.read_shp(path)
G=layer.to_undirected()

After manipulating its edge attributes, I have to keep the results in a shapefile, so:

nx.write_shp(G,out_path)

The problem is, this new shapefile will have completely random order of attributes; understandable, since the attributes are stored in a dictionary. I couldn't fix this with OrderedDict either:

# Does NOT work
for edge in G.edges(data=True):
    edge = list(edge)
    edge[2] = OrderedDict(sorted(edge[2].items()))
    edge=tuple(edge)

Is there a way to sort, or change the order of attributes for each edge?

Was it helpful?

Solution

This:

for edge in G.edges(data=True):
    edge = list(edge)
    edge[2] = OrderedDict(sorted(edge[2].items()))
    edge=tuple(edge)

has no effect on the output (or the contents of the object pointed to by G), because by doing:

edge = tuple(edge)

you are only modifying the local variable edge; this will not affect the value returned by G.edges(data=True), even less the internal state of G. This holds for any (Python) program whatsoever and is in no way related to networkx or your program specifically.

So unless you write your own algorithm to serialize and dump the data to a file, or unless you can tell networkx how it should serialize the data, there's no way to change the file content. ...unless I'm missing something, that is, but according to http://networkx.lanl.gov/reference/readwrite.nx_shp.html, write_shp is not configurable in the manner you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top