给定一个值,使用Networkx选择一个属性。蟒蛇

时间:2018-12-31 05:24:20

标签: python networkx

您如何告诉Networkx,给定一个属性,再选择一个?更准确地说,我有以下数据:

Final_s1 = G.node[node]['s1']
Initial_s1 = G.node['a']['s1']

Final_s2 = G.node[node]['s2']
Initial_s2 = G.node['a']['s2']

我执行一些简单的计算

Perf_s1 = (Final_s1 - Initial_s1)/Initial_s1
Perf_s2 = (Final_s2 - Initial_s2)/Initial_s2

我想看看是否有什么方法可以省略下两行:

G.node[node]['Perf_s1'] = Perf_s1
G.node[node]['Perf_s2'] = Perf_s2

接下来,我找到两个“表演”之间的最小值:

min_node = min(['Perf_s1', 'Perf_s2'], key=lambda x: G.node[node][x])

最后一部分是我想学习如何更好地编程的内容。它可以工作,但是必须添加两个其他属性和if-else语句似乎并不是最好的选择。

if min_node == 'Perf_s1':
    Initial_Worst = G.node['a']['s1']
    Final_Worst = G.node[node]['s1']
    G.node[node]['value'] = Initial_Worst * Final_Worst
else:
    Initial_Worst = G.node['a']['s2']
    Final_Worst = G.node[node]['s2']
    G.node[node]['value'] = Initial_Worst*Final_Worst

谢谢!

1 个答案:

答案 0 :(得分:0)

Networkx不支持这种开箱即用的计算(有理由)。节点的属性只是保存为字典,将属性的名称映射到值。您可以使用简单的python代码以更通用的方式完成操作。 这是我的建议:

import random
import networkx as nx

# Generate a random graph with some values for s1 and s2:
G = nx.erdos_renyi_graph(10, 0.25)
nx.set_node_attributes(G, {node: {'s1': random.randint(0, 100), 's2': random.randint(0, 100)} for node in G.nodes()})
# Choose some node 'a' (the initial node):
a = 0
# Define the metrics we are interested at:
metrics = ['s1','s2']
# For each node compute and add the value:
for node in G.nodes():
    # Compute the metrics (i.e., Perf_s1 and Perf_s2), keep in a dictionary:
    metrics_dict = {metric: (G.node[node][metric] - G.node[a][metric]) / G.node[a][metric] for metric in metrics}
    # Get the metric that minimizes the desired value (e.g., 's1'):
    arg_min = min(metrics_dict, key=metrics_dict.get)
    # Add as an attribute to the graph under 'value':
    nx.set_node_attributes(G, {node : {'value': G.node[node][arg_min] * G.node[a][arg_min]}})