在for循环中构建不同的networkx图

时间:2018-06-18 14:16:21

标签: python pandas for-loop networkx

我有一个大熊猫数据框,我必须从中提取几个网络,每次都考虑数据帧的一个子集。这些图将是二分图,因此将有两组节点(数据集中的两列),nodes_x和nodes_y。我想在循环中构建图形,而不是手动完成。如何以递归方式为每个图表指定名称?

解释一段代码:

import pandas as pd
import networkx as nx

df=pd.read_csv('my_dataframe')

sub_list=df.nodes_y.unique()

for item in sub_list:
    sub_df=df[df['nodes_y']==item]
    sG_*item*=nx.Graph() #here I'd like to assign a name to the network 
                         #recursively based on the subset of the dataframe
    sG_*item*.add_nodes_from(sub_df['nodes_x'])
    sG_*item*.add_nodes_from(sub_df['nodes_y'])
##rest of the code

最重要的是,这是一种可行且可取的操作方式吗?我的问题有更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

让我们尝试使用字典而不是新变量:

import pandas as pd
import networkx as nx

df=pd.read_csv('my_dataframe')

sub_list=df.nodes_y.unique()
sg_dict = {}


for item in sub_list:
    sub_df=df[df['nodes_y']==item]
    sG_dict[item]=nx.Graph() #here I'd like to assign a name to the network 
                         #recursively based on the subset of the dataframe
    sG_dict[item].add_nodes_from(sub_df['nodes_x'])
    sG_dict[item].add_nodes_from(sub_df['nodes_y'])
##rest of the code