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

Pythonic way to convert Pandas dataframe from wide to long

I have a JSON file, which I then convert to a Pandas dataframe called stocks. The stocks dataframe is in wide format and I’d like to convert it to long format.

Here’s what the stocks dataframe looks like after it’s ingested and converted from JSON:

    TSLA     MSFT     GE      DELL 
0   993.22   320.72   93.19   57.25

I would like to convert the stocks dataframe into the following format:

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

     ticker   price
0    TSLA     993.22  
1    MSFT     320.72
2    GE       93.19
3    DELL     57.25

Here is my attempt (which works):

stocks = pd.read_json('stocks.json', lines=True).T.reset_index()
stocks.columns = ['ticker', 'price']

Is there a more Pythonic way to do this? Thanks!

>Solution :

pandas provides the melt function for this job.

pd.melt(stocks, var_name="ticker", value_name="price")
#  ticker   price
#0   TSLA  993.22
#1   MSFT  320.72
#2     GE   93.19
#3   DELL   57.25
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