如何从networkx中的图形中删除float('nan')节点? [英] How to remove float('nan') node from a graph in networkx?
问题描述
我有一个包含 float('nan')
的数据集(pickle 格式),我需要删除它.
可以将 float('nan')
作为 networkx 中的节点添加到图中.但是,我不知道如何删除它.
将 networkx 导入为 nxG = nx.Graph()G.add_node(float('nan'))print(G.nodes) # [nan],所以图中有float('nan')G.remove_node(float('nan')) # 这个语句引发了一个 NetworkxError,显示 nan 不在图中
CoReRank-WSDM-2019 和 中的代码和数据="https://bhooi.github.io/code/birdnest.zip" rel="nofollow noreferrer">鸟巢.
有人能帮我解决这个问题吗?提前致谢.
我们可以在一个简单的字典上进行测试,它是 NetworkX 图的底层数据结构.假设您有:
d = {'a':3, float('nan'):4}
如果我们像您一样尝试访问 NaN
键:
d[float('nan')]>关键错误:nan
造成这种情况的核心原因是 NaN
不等于自身:
这导致查找失败的原因,在这里有很好的解释.
一种解决方法,可能是遍历图形键,并识别 NaN
节点,然后然后使用对象的相同引用删除该键:
导入数学G = nx.Graph()G.add_node(float('nan'))G.add_node(3)打印(G.nodes)# [南, 3]nan_nodes = []对于 G.nodes() 中的节点:如果 math.isnan(节点):nan_nodes.append(节点)G.remove_nodes_from(nan_nodes)G.nodes()# NodeView((3,))
I have a dataset(pickle format) containing float('nan')
, and I need to remove it.
It is possible to add float('nan')
to a graph as a node in networkx. However, I don't know how to remove it.
import networkx as nx
G = nx.Graph()
G.add_node(float('nan'))
print(G.nodes) # [nan], so there is float('nan') in the graph
G.remove_node(float('nan')) # this statement raise a NetworkxError showing nan not in the graph
Code and data in CoReRank-WSDM-2019 and BirdNest.
Could anyone help me with this problem? Thank you in advance.
We can test this on a simple dictionary, which is the underlying data structure of a NetworkX graph. Say you have:
d = {'a':3, float('nan'):4}
If we try accessing the NaN
key, as you're trying to do:
d[float('nan')]
> KeyError: nan
The core cause of this, is explained by the fact that a NaN
does not equal to itself:
>>> float("nan") == float("nan")
False
The reason behind why this causes the lookup to fail, is nicely explained here.
A workaround, could be to loop over the graph keys, and identify the NaN
node and then remove that key using the same reference of the object:
import math
G = nx.Graph()
G.add_node(float('nan'))
G.add_node(3)
print(G.nodes)
# [nan, 3]
nan_nodes = []
for node in G.nodes():
if math.isnan(node):
nan_nodes.append(node)
G.remove_nodes_from(nan_nodes)
G.nodes()
# NodeView((3,))
这篇关于如何从networkx中的图形中删除float('nan')节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!