在networkx中移除特定范围内权重的边

0 投票
2 回答
4362 浏览
提问于 2025-06-18 04:00

我有一个数据框(dataframe)。我把这个数据框转换成了一个图(graph)。之后,我想要删除一些特定权重范围内的边(edges):

列:

df.columns:
Index(['source', 'target', 'weight'], dtype='object')

长度:

len(df)
1048575

数据类型:

df.dtypes
source      int64
target    float64
weight      int64
dtype: object

现在,构建一个networkx图:

Graphtype = nx.Graph()
G = nx.from_pandas_edgelist(df, 'source','target', edge_attr='weight', create_using=Graphtype)

图的信息:

print(nx.info(G))
Name: 
Type: Graph
Number of nodes: 609627
Number of edges: 915549
Average degree:   3.0036

度数:

degrees = sorted(G.degree, key=lambda x: x[1], reverse=True)
degrees
[(a, 1111),
 (c, 1107),
 (f, 836),
 (g, 722),
 (h, 608),
 (k, 600),
 (r, 582),
 (z, 557),
 (l, 417), etc....

我想做的是删除特定权重的边。比如,我想删除所有权重大于等于500的边。

to_remove = [(a,b) for a,b in G.edges(data=True) if "weight" >= 500]
G.remove_edges_from(to_remove)

但是,我收到了以下错误信息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-df3a67f18df9> in <module>()
----> 1 to_remove = [(a,b) for a,b in G.edges(data=True) if "weight" >=500]

<ipython-input-12-df3a67f18df9> in <listcomp>(.0)
----> 1 to_remove = [(a,b) for a,b in G.edges(data=True) if "weight" >=500]

ValueError: too many values to unpack (expected 2)

有没有人知道我为什么会收到这个信息?或者说,是否有更好的方法来做到这一点?谢谢!

相关问题:

  • 暂无相关问题
暂无标签

2 个回答

3

这是我解决这个问题的方法:

threshold = 500

# filter out all edges above threshold and grab id's
long_edges = list(filter(lambda e: e[2] > threshold, (e for e in G.edges.data('weight'))))
le_ids = list(e[:2] for e in long_edges)

# remove filtered edges from graph G
G.remove_edges_from(le_ids)
3

在这个理解中,你把一个字符串“weight”和一个整数进行比较,这样做其实没有什么意义:

[(a,b) for a,b in G.edges(data=True) if "weight" >= 500]

另外,真正导致异常的原因是,如果你传入 data=True,你会得到一个三元组,其中第三个元素是一个属性的字典。

你可能想要做的是:

[(a,b) for a, b, attrs in G.edges(data=True) if attrs["weight"] >= 500]

撰写回答