2

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

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

Short answer:

df = pd.read_csv('file.csv', parse_dates=True, index_col=0, header=None).rename_axis(
index='date').rename(columns={1: 'bid', 2: 'ask'}).reindex(
columns=pd.MultiIndex.from_product([['JAS'], ['bid', 'ask']]), level=1)

Out[1]: 
           JAS        
           bid     ask
date                      
2011-06-04  104.64  105.17
2011-07-04  104.98  105.51
2011-08-04  105.43  105.96
2011-11-04  104.47  104.99

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.