如何从networkx图中提取随机节点?

10
如何从networkx图中提取随机节点?我有一个以networkx图形式呈现的地图,我必须从中提取5个随机节点并获取与每个节点及其边缘相关的数据。我认为我可以使用“np.random.choice”来实现,但仍然无法获得任何结果。

1
请发布您的代码。 - Eric Hauenstein
相关的新问题:https://stackoverflow.com/questions/48598324/g-nodes-from-networkx-is-not-working-with-random-choice - dasWesen
3个回答

5

24
随着networkx 2.0的发布,这不再起作用。你可以使用choice(list(g.nodes))代替。 - Carl
1
@Carl 请将此作为答案发布。 - Code-Apprentice
@Code-Apprentice 已发布答案。 - Carl

4

请使用sample方法,而不是使用choice方法。

from random import sample
import os
import networkx as nx

# load a graph from local
working_path = r'XXX'
graph = nx.read_gexf(os.path.join(working_path, 'XXX.gexf'))
# random sample 3 nodes from the graph
random_nodes = sample(list(graph.nodes()), 3)

如果您有一个包含不同节点类型的图形 g,您可以使用下面的函数来计算具有特定类型的节点数:

def count_nodes_with_type(graph, attribute_name, query):
    """
    Count the number of nodes with specific type
    :param graph: a networkx graph whose nodes have several different types
    :param attribute_name: the attribute name used to access different type of nodes
    :param query: the search query
    :return: number of nodes satisfying the query
    """
    node_attribute_dict = nx.get_node_attributes(graph, attribute_name)
    filtered_nodes = {key: value for (key, value) in node_attribute_dict.items() if value == query}
    return len(filtered_nodes)

你可以使用相同的逻辑,使用 nx.get_edge_attributes 方法来计算特定类型的边的数量。

2

最近版本的NetworkX(我认为是>= 2.5)中,您可以直接在节点视图上使用random.sample()来获取节点的标签/索引或标签和数据的样本。

import networkx as nx
import random as rd

# Generate the example Karate club graph provided in NetworkX
g = nx.karate_club_graph()
print(g.nodes)  # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]

# Get a random sample (without replacement) of the node labels/indexes:
sample = rd.sample(g.nodes, 3)
print(sample)  # Output: [22, 18, 6]

# Get a random sample (without replacement) of the node labels and data:
sample = rd.sample(g.nodes.items(), 3)
print(sample)  # Output: [(24, {'club': 'Officer'}), (27, {'club': 'Officer'}), (31, {'club': 'Officer'})]

在稍早的版本中(从2.0但在2.5之前),您需要将节点视图转换为列表,然后再使用random.sample
注意:如果您安装了最新的NetworkX包,则无需担心此问题。
# Get a random sample (without replacement) of the node labels/indexes
# in older version of NetworkX.
sample = rd.sample(list(g.nodes), 3)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接