Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 284
Will H Avatar asked Jun 11 '14 16:06

Will H


People also ask

How do I create a CSV file using pandas in Python?

By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.

Does CSV have metadata?

Many "CSV" files embed metadata, for example in lines before the header row of the CSV document.

Does pandas To_csv overwrite?

If the file already exists, it will be overwritten. If no path is given, then the Frame will be serialized into a string, and that string will be returned.

What does To_csv do in pandas?

Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.


1 Answers

>>> with open('test.csv', 'w') as fout:
...      fout.write('meta data\n:')
...      meta_data.to_csv(fout)
...      ts.to_csv(fout)
like image 54
behzad.nouri Avatar answered Sep 28 '22 22:09

behzad.nouri