Anirudh Murali
Anirudh Murali

Reputation: 107

How to ungroup Column groups and covert them into rows using pandas?

I have the following table from downloading stock data downloaded for multiple stocks. I used the following code

i = ['NTPC.NS', 'GAIL.NS']
stock = yf.download(tickers=i, start='2021-01-11', end='2021-03-10', interval = '5m', group_by = 'tickers')

The output dataframe looks like this

enter image description here

But I want the output to be like this

enter image description here

Upvotes: 1

Views: 175

Answers (1)

jezrael
jezrael

Reputation: 862481

Use DataFrame.stack by first level, then rename index names and convert last level of MultiIndex to column by DataFrame.reset_index:

df = stock.stack(level=0).rename_axis(['Datetime','stockname']).reset_index(level=-1)
#if necessary change order of columns
df = df[df.columns.tolist()[1:] + df.columns.tolist()[:1]]

Upvotes: 1

Related Questions