Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python NetworkX/Pandas-如何将每个节点的社区组输出为.txt_Python_Pandas_Networkx - Fatal编程技术网

Python NetworkX/Pandas-如何将每个节点的社区组输出为.txt

Python NetworkX/Pandas-如何将每个节点的社区组输出为.txt,python,pandas,networkx,Python,Pandas,Networkx,我需要将网络中每个节点的社区输出到一个.txt文件中。 我正在使用NetworkX版本。2.1和1。0.23.4: import networkx as nx import pandas as pd from networkx.algorithms import community G = nx.barbell_graph(5, 1) communities_generator = community.girvan_newman(G) top_level_communities = next(

我需要将网络中每个节点的社区输出到一个.txt文件中。 我正在使用NetworkX版本。2.1和1。0.23.4:

import networkx as nx
import pandas as pd
from networkx.algorithms import community

G = nx.barbell_graph(5, 1)
communities_generator = community.girvan_newman(G)
top_level_communities = next(communities_generator)
next_level_communities = next(communities_generator)
sorted(map(sorted, next_level_communities))

#>>> sorted(map(sorted, next_level_communities))
[[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]]
#in this case, 3 different communities (groups) were identified
我需要一个类似以下内容的.txt表:

NODE    COMMUNITY
0   GROUP 1
1   GROUP 1
2   GROUP 1
3   GROUP 1
4   GROUP 1
5   GROUP 2
6   GROUP 3
7   GROUP 3
8   GROUP 3
9   GROUP 3
10  GROUP 3

您可以这样做:

import networkx as nx
import pandas as pd
from networkx.algorithms import community

G = nx.barbell_graph(5, 1)
communities_generator = community.girvan_newman(G)
top_level_communities = next(communities_generator)
next_level_communities = next(communities_generator)

data = [[element, "GROUP-{}".format(ii + 1)] for ii, st in enumerate(next_level_communities) for element in sorted(st)]
print(data)

frame = pd.DataFrame(data=data, columns=['node', 'community'])
frame.to_csv("communities.csv", sep=" ", index=False)
“communities.csv”文件的格式如下:

node community
0 GROUP-1
1 GROUP-1
2 GROUP-1
3 GROUP-1
4 GROUP-1
5 GROUP-2
6 GROUP-3
7 GROUP-3
8 GROUP-3
9 GROUP-3
10 GROUP-3