How to read csv file into pandas DataFrame with multiple row index level?
pandas, python
Solution
Read the CSV, setting the first (0th) columns as the index.
In [8]: df = pd.read_csv(StringIO("""06/04/2011,104.64,105.17
07/04/2011,104.98,105.51
08/04/2011,105.43,105.96
11/04/2011,104.47,104.99"""), index_col=0, header=None)
Create a new MultiIndex, and assign it to the columns.
In [11]: df.columns = pd.MultiIndex.from_tuples([('JAS', 'bid'), ('JAS', 'ask')])
Finally, name the index, and we have your desired result.
In [12]: df.index.name = 'date'
In [13]: df
Out[13]:
JAS
bid ask
date
06/04/2011 104.64 105.17
07/04/2011 104.98 105.51
08/04/2011 105.43 105.96
11/04/2011 104.47 104.99
Problem
The original csv file data is like that: ``` 06/04/2011,104.64,105.17 07/04/2011,104.98,105.51 08/04/2011,105.43,105.96 11/04/2011,104.47,104.99 ``` How to either read the csv file into DataFrame and add multiple row index level, or add multiple row index into csv and import into DataFrame as following: ``` JAS date bid ask 06/04/2011 104.64 105.17 07/04/2011 104.98 105.51 08/04/2011 105.43 105.96 11/04/2011 104.47 104.99 ```