0

I have a df which looks like:

enter image description here

Let the group name of the individual columns be 'Symbol', so that a list of column names 'Symbol' = ['AAPL US Equity', 'ABT US Equity', 'BDX US Equity', 'BRO US Equity'] Let 'Returns' be the floats. Let 'Dates' be a datetime index.

Question: I need the df to have MultiIndex of ['Ticker', 'Dates'] with the hierarchy of it being the order i.e. 'Ticker' --> 'Dates' --> 'Returns'

Something like:

enter image description here

It is first grouped by 'Symbol', then by 'Date'

1 Answer 1

1

Use DataFrame.unstack :

df = df.set_index('Dates').unstack().rename_axis(['Symbol','Date']).to_frame('Close')

Or DataFrame.melt:

df = (df.melt('Dates', var_name='Symbol', value_name='Close')
        .set_index(['Symbol','Dates'])
        .sort_index())
Sign up to request clarification or add additional context in comments.

1 Comment

Both work! The DataFrame.melt method keeps it as a DataFrame which I need later. Thank you!

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.