Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reshape a pandas dataframe specific format

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading