问题
I am trying to create a csv file that contains metadata in the first few rows, followed by timeseries data, so it can be processed by another web application. My csv file should look like this:
Code: ABC1
Frequency: Monthly
Description: Blah Blah
-------------------
2/1/1947 11.7
3/1/1947 11.9
I can create a csv file of the metadata:
metadata=pd.Series([('code: ABC123'),('freqency: monthly'),('description: describecode'),('--------')])
metadata.to_csv("metadata.csv",index=False)
I can create a csv of the timeseries
a=pd.Series((11.7,11.9),index=pd.date_range('1947-01-02','1947-01-03'))
a.to_csv("data.csv")
But I can't work out how to merge them together into the format at the top.
回答1:
>>> with open('test.csv', 'w') as fout:
... fout.write('meta data\n:')
... meta_data.to_csv(fout)
... ts.to_csv(fout)
回答2:
You might be better off using DictWriter
toCSV = [] #put all your data in a list of Dictionaries such as {'Date': ... etc}
keys = ['Date', .... ] #list of keys for data
file = open( filename.csv, 'wb')
dict_writer = csv.DictWriter(file, keys)
dict_writer.writer.writerow(Metadata)
dict_writer.writerows(toCSV)
file.close()
the keys create a number of columns and then the writer writes in your data (in dictionaries) according to the keys.
来源:https://stackoverflow.com/questions/24168507/create-csv-file-with-metadata-header-followed-by-timeseries-in-python-pandas