简体   繁体   English

networkx删除节点属性

[英]networkx remove node attribute

i have attached numpy-array to nodes in a networkx graph. 我已经将numpy-array附加到networkx图中的节点。 How to store the graph in gexf-format on disk? 如何在磁盘上以gexf格式存储图形? (without the numpy vector, as its just something intermediate...) (没有numpy向量,因为它只是中间的东西...)

def create():
    G = nx.Graph()
    for i in range(256):
        G.add_node(i, vector=np.arange(20))
    for i in range(1,20):
        for j in range(1,256, 10):
            G.add_edge(i,j)

    temp = tempfile.mktemp(suffix=".gexf")
    print("dumping G = (V: %s, E: %s) to disk %s"
        % (len(G.nodes()), len(G.edges()), temp))
    nx.write_gexf(G, temp)

However, this breaks. 但是,这打破了。 I'm new to python, but to me it seems like the ndarray is not serializable?! 我是python的新手,但对我来说ndarray似乎不可序列化? So, how to tell networkx to ignore that node attribute? 那么,如何告诉networkx忽略该节点属性?

File "...lib\site-packages\networkx\readwrite\gexf.py", line 430, in add_attributes
    attr_id = self.get_attr_id(make_str(k), self.xml_type[val_type],
KeyError: <type 'numpy.ndarray'>

Use a library like the native pickle , or h5py for HDF5, to serialize your graph object. 使用本机pickle类的库,或对HDF5使用h5py类的库来序列化图形对象。 For example you can do: 例如,您可以执行以下操作:

import pickle

with open("pickle_file", "wb") as f:
    pickle.dump(create(), f)

The pickled graph can be loaded back into Python by: 可以通过以下方法将腌制后的图加载回Python:

with open("pickle_file", "rb") as f:
    G = pickle.load(f)

I solved this by removing the property "vector" from the data items: 我通过从数据项中删除属性“ vector”来解决此问题:

for (n,d) in G.nodes(data=True):
    del d["vector"]

full MWE: 完整的MWE:

def create():
    G = nx.Graph()
    for i in range(256):
        G.add_node(i, vector=np.arange(20))
    for i in range(1,20):
        for j in range(1,256, 10):
            G.add_edge(i,j)

    temp = tempfile.mktemp(suffix=".gexf")
    print("dumping G = (V: %s, E: %s) to disk %s"
        % (len(G.nodes()), len(G.edges()), temp))
    for (n,d) in G.nodes(data=True):
        del d["vector"]
    nx.write_gexf(G, temp)

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

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