撰写《字典词典》,到特定格式的.csv文件
问题描述:
我正在从多个.csv文件中生成一个字典,它看起来像这样(示例):
I am generating a dictionary out of multiple .csv files and it looks like this (example):
dtDict = {'AV-IM-1-13991730': {'6/1/2014 0:10': '0.96',
'6/1/2014 0:15': '0.92',
'6/1/2014 0:20': '0.97'},
'AV-IM-1-13991731': {'6/1/2014 0:10': '1.96',
'6/1/2014 0:15': '1.92',
'6/1/2014 0:20': '1.97'},
'AV-IM-1-13991732': {'6/1/2014 0:10': '2.96',
'6/1/2014 0:15': '2.92',
'6/1/2014 0:20': '2.97'},
'AV-IM-1-13991733': {'6/1/2014 0:10': '3.96',
'6/1/2014 0:15': '3.96',
'6/1/2014 0:20': '3.97'}}
我想将其保存为以下格式的.csv文件:
I want to save it to a .csv file in the following format:
timestamp,AV-IM-1-13991730,AV-IM-1-13991731,AV-IM-1-13991732,AV-IM-1-13991733
6/1/2014 0:10,0.96,1.96,2.96,3.96
6/1/2014 0:15,0.92,1.92,2.92,3.96
6/1/2014 0:20,0.97,1.97,2.97,3.97
到目前为止,我拥有的这段代码(与该目标有关):
The piece of code I have as of now (related to this objective):
header = '''# file...... Recorder file
# date...... Thu Mar 12 14:35:32 2015
# user...... Sri
# host...... (null)
# group..... None
# property.. AVA Measurements
# limit.....
# interval..'''
testpower = open("custpower.csv",'w')
testpower.writelines([header,'\n','# timestamp\n'])
...
for key, value in dtDict.iteritems():
#Still trying to figure out how to write to custpower.csv
我尝试做类似的事情:
for key, value in dtDict.iteritems():
testpower.writelines([key,',',','.join(value),'\n'])
但是它并没有完全按照我的意图做.
but it didnot quite do what I was trying to do.
答
如果可以使用pandas
,这将非常简单.
This is beyond simple if you can use pandas
.
import pandas as pd
data = {'AV-IM-1-13991730': {'6/1/2014 0:10': '0.96',
'6/1/2014 0:15': '0.92',
'6/1/2014 0:20': '0.97'},
'AV-IM-1-13991731': {'6/1/2014 0:10': '1.96',
'6/1/2014 0:15': '1.92',
'6/1/2014 0:20': '1.97'},
'AV-IM-1-13991732': {'6/1/2014 0:10': '2.96',
'6/1/2014 0:15': '2.92',
'6/1/2014 0:20': '2.97'},
'AV-IM-1-13991733': {'6/1/2014 0:10': '3.96',
'6/1/2014 0:15': '3.96',
'6/1/2014 0:20': '3.97'}}
df = pd.DataFrame(data)
df.to_csv(PATH_TO_OUTPUT_FILE)
df
变成一个看起来像
AV-IM-1-13991730 AV-IM-1-13991731 AV-IM-1-13991732 AV-IM-1-13991733
6/1/2014 0:10 0.96 1.96 2.96 3.96
6/1/2014 0:15 0.92 1.92 2.92 3.96
6/1/2014 0:20 0.97 1.97 2.97 3.97
您生成的csv看起来像
And your resulting csv looks like
,AV-IM-1-13991730,AV-IM-1-13991731,AV-IM-1-13991732,AV-IM-1-13991733
6/1/2014 0:10,0.96,1.96,2.96,3.96
6/1/2014 0:15,0.92,1.92,2.92,3.96
6/1/2014 0:20,0.97,1.97,2.97,3.97
熊猫也很好,因为您可以这样做:
Pandas is also nice because you can then do:
df.convert_objects(convert_numeric=True).plot()
# the converts change "0.97" -> 0.97 so it's plottable
获得: