gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:49:10 25 4
gpt4 key购买 nike

我有一个 Pandas 数据框,我必须从中提取多个网络,每次都考虑数据框的子集。这些图将是二分图,因此将有两组节点(数据集中的两列):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

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

最佳答案

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

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

关于python - 在 for 循环中构建不同的 networkx 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50911501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com