Вам просто нужно добавить []
к вашему remove_edges_from
вызову (и вы должны вернуть F
вместо G
. Из вашего другого вопроса я создал минимальный воспроизводимый пример:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
simple_weights = [[1., 0.51639778, 0., 0., 0., 0.],
[0.51639778, 1., 0., 0., 0., 0.25819889],
[0., 0., 1., 0., 0., 0.33333333],
[0., 0., 0., 1., 0.65465367, 0.],
[0., 0., 0., 0.65465367, 1., 0.],
[0., 0.25819889, 0.33333333, 0., 0., 1.]]
G = nx.from_numpy_matrix(np.array(simple_weights), create_using=nx.DiGraph)
nx.draw(G)
plt.show()
F = G.copy()
threshold = 0.4
F.remove_edges_from([(n1, n2) for n1, n2, w in F.edges(data="weight") if w < threshold])
nx.draw(F)
plt.show()
или как ваша функция (вы не определили copy
в своем коде выше)
def slice_network(G, T, data = True):
""" Remove all edges with weight<T from G or its copy. """
F = G.copy() if copy else G
F.remove_edges_from([(n1, n2) for n1, n2, w in F.edges(data="weight") if w < T])
return F
или как фильтр перед созданием
threshold = 0.4
simple_weights = np.array(simple_weights)
simple_weights[simple_weights<threshold] = 0