我有一个加权的Networkx图G。我首先想对G做一些加权操作(这就是为什么我不读取输入并设置weights=None),然后从G中删除它们。最直截了当的方法是什么使它不加权?
我可以这么做:
G = nx.from_scipy_sparse_array(nx.to_scipy_sparse_array(G,weight=None))
或者循环遍历G.adj字典并设置weights=0,但这两个选项都感觉太复杂了。类似于:
G = G.drop_weights()
发布于 2022-11-23 01:32:21
可以直接访问networkx图形的数据结构,并删除任何不必要的属性。最后,您可以做的是定义一个函数,该函数遍历字典并删除“权重”属性。
def drop_weights(G):
'''Drop the weights from a networkx weighted graph.'''
for node, edges in nx.to_dict_of_dicts(G).items():
for edge, attrs in edges.items():
attrs.pop('weight', None)
还有一个用法的例子:
import networkx as nx
def drop_weights(G):
'''Drop the weights from a networkx weighted graph.'''
for node, edges in nx.to_dict_of_dicts(G).items():
for edge, attrs in edges.items():
attrs.pop('weight', None)
G = nx.Graph()
G.add_weighted_edges_from([(1,2,0.125), (1,3,0.75), (2,4,1.2), (3,4,0.375)])
print(nx.is_weighted(G)) # True
F = nx.Graph(G)
print(nx.is_weighted(F)) # True
# OP's suggestion
F = nx.from_scipy_sparse_array(nx.to_scipy_sparse_array(G,weight=None))
print(nx.is_weighted(F)) # True
# Correct solution
drop_weights(F)
print(nx.is_weighted(F)) # False
请注意,即使不通过nx.to_scipy_sparse_array
重构没有权重的图也是不够的,因为图是用权重构造的,只有这些设置为1。
https://stackoverflow.com/questions/72045825
复制相似问题