Create a csv file with a metadata header followed by timers in Python / Pandas

I am trying to create a csv file containing metadata in the first few lines followed by temporary 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 metadata file:

metadata=pd.Series([('code: ABC123'),('freqency: monthly'),('description: describecode'),('--------')])

metadata.to_csv("metadata.csv",index=False)

I can create csv time series

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 figure out how to combine them together in a format at the top.

+4
source share
2 answers
>>> with open('test.csv', 'w') as fout:
...      fout.write('meta data\n:')
...      meta_data.to_csv(fout)
...      ts.to_csv(fout)
+1
source

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 several columns, and then the entries are written to your data (in dictionaries) according to the keys.

0

Source: https://habr.com/ru/post/1544200/


All Articles