Home > OS >  How to reshape a pandas dataframe specific format
How to reshape a pandas dataframe specific format

Time:01-31

I have the following code in python which is a simple Dataframe that produces the result in the image on the left side, and I would like to reshape the Dataframe so that it produces the output that is in the right side

Is there a way to do it without looping multiple times through the Dataframe?

import pandas as pd

df = pd.DataFrame({'symbol':['AAPL','AAPL','AAPL','AAPL','AAPL','BYND','BYND','BYND']
    ,'quarter':['2019Q1', '2019Q2', '2019Q3', '2019Q4', '2020Q1', '2019Q3', '2019Q4', '2020Q1']
    , 'change_pct':[.5, .3, .1, .4, 0, .8, .2, .3]})

Dataframe desired output enter image description here

CodePudding user response:

Use can use pivot for this:

df = pd.DataFrame({'symbol':['AAPL','AAPL','AAPL','AAPL','AAPL','BYND','BYND','BYND']
    ,'quarter':['2019Q1', '2019Q2', '2019Q3', '2019Q4', '2020Q1', '2019Q3', '2019Q4', '2020Q1']
    , 'change_pct':[.5, .3, .1, .4, 0, .8, .2, .3]})
df = df.pivot(index = 'symbol',columns='quarter',values='change_pct').fillna('')
print(df)

Prints:

quarter 2019Q1 2019Q2  2019Q3  2019Q4  2020Q1
symbol                                       
AAPL       0.5    0.3     0.1     0.4     0.0
BYND                      0.8     0.2     0.3

CodePudding user response:

You can do this with pd.Dataframe.pivot - something like

pivoted = df.pivot(index=symbol, columns=quarter, values=change_pct)
  •  Tags:  
  • Related