[英]How to write a Dictionary to Excel in Python
I have the following dictionary in python that represents a From - To Distance Matrix. 我在python中有以下字典表示From-To Distance Matrix。
graph = {'A':{'A':0,'B':6,'C':INF,'D':6,'E':7},
'B':{'A':INF,'B':0,'C':5,'D':INF,'E':INF},
'C':{'A':INF,'B':INF,'C':0,'D':9,'E':3},
'D':{'A':INF,'B':INF,'C':9,'D':0,'E':7},
'E':{'A':INF,'B':4,'C':INF,'D':INF,'E':0}
}
Is it possible to output this matrix into excel or to a csv file so that it has the following format? 是否可以将此矩阵输出到excel或csv文件中,以便它具有以下格式? I have looked into using csv.writer and csv.DictWriter but can not produce the desired output. 我已经研究过使用csv.writer和csv.DictWriter但是无法生成所需的输出。
You may create a pandas dataframe from that dict, then save to CSV or Excel: 您可以从该dict创建一个pandas数据框,然后保存为CSV或Excel:
import pandas as pd
df = pd.DataFrame(graph).T # transpose to look just like the sheet above
df.to_csv('file.csv')
df.to_excel('file.xls')
Probably not the most minimal result, but pandas would solve this marvellously (and if you're doing data analysis of any kind, I can highly recommend pandas!). 可能不是最小的结果,但是大熊猫会很好地解决这个问题(如果你正在做任何类型的数据分析,我强烈推荐大熊猫!)。
Your data is already in a perfectformat for bringing into a Dataframe 您的数据已经处于完美格式中,无法引入Dataframe
INF = 'INF'
graph = {'A':{'A':0,'B':6,'C':INF,'D':6,'E':7},
'B':{'A':INF,'B':0,'C':5,'D':INF,'E':INF},
'C':{'A':INF,'B':INF,'C':0,'D':9,'E':3},
'D':{'A':INF,'B':INF,'C':9,'D':0,'E':7},
'E':{'A':INF,'B':4,'C':INF,'D':INF,'E':0}
}
import pandas as pd
pd.DataFrame(graph).to_csv('OUTPUT.csv')
but the output you want is this Transposed, so: 但你想要的输出是这个Transposed,所以:
pd.DataFrame(graph).T.to_csv('OUTPUT.csv')
where T returns the transpose of the Dataframe. 其中T返回Dataframe的转置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.