Python output multiple dictionaries into the same CSV file

This is mainly to calculate the degree of each node in the network, then save it as a node, and then output each degree to the same csv file, as
shown below:

{
    
    '上海绿泰宝营养保健品有限公司': 0.00018777579569993427, 'stevia aps': 4.694394892498357e-05, '中国科学院上海药物研究所': 0.097127030325791, 'ufc limited': 4.694394892498357e-05}

Among them, the edge betweenness centrality dictionary uses two nodes as keys, so it is output as a csv separately.

{
    
    ('上海绿泰宝营养保健品有限公司', 'stevia aps'): 2.8175522233304593e-06, ('上海绿泰宝营养保健品有限公司', 'stevia limited'): 2.8175522233304593e-06, ('中国科学院上海药物研究所', 'ufc limited'): 0.0014749885889134954, ('中国科学院上海药物研究所', 'bayer ag'): 0.028678449776089222

In addition, the df when reading the file, because the UTF-8, gbk, and gb2312 encodings used before are easy to report errors (because the strings in the data are more complicated), so here we use gb18030, which contains more characters, see: https: //blog.csdn.net/Junkichan/article/details/51913845This blog post.
The specific code is as follows

import pandas as pd
import networkx as nx
import csv
df=pd.read_csv("E:/数据a.csv",encoding='gb18030')
#df=pd.read_excel("E:/数据a.xlsx")
#也可以是读取excel文件,要注意,如果你的pandas版本比较老,是无法用encoding的
g=nx.from_pandas_edgelist(df,"Source","Target",create_using=nx.Graph)
degre_cen=dict(nx.degree_centrality(g))#度中心性
close_cen=dict(nx.closeness_centrality(g))#接近度中心性
node_betwe_cen=dict(nx.betweenness_centrality(g))#节点介数中心性
edge_betwe_cen=dict(nx.edge_betweenness_centrality(g))#边介数中心性
# 创建字典列表
dict_list = [degre_cen,close_cen,node_betwe_cen]
# 获取所有字典的键名
keys = set().union(*(d.keys() for d in dict_list))
# 打开 CSV 文件并将字典按行输出到文件中
with open('E:/output1.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    # 写入表头
    writer.writerow(['Name','degre_cen','close_cen','node_betwe_cen'])
    # 按行输出字典
    for key in keys:
        row = [key]
        for d in dict_list:
            if key in d:
                row.append(d[key])
            else:
                row.append('')
        writer.writerow(row)
with open('E:/output2.csv', mode='w', newline='') as f:
    writer = csv.writer(f)
    for row in edge_betwe_cen.items():
        writer.writerow(row)

Guess you like

Origin blog.csdn.net/c6983127/article/details/129460608