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 can I reshape a wide CSV table using python?

This question is about reshaping data from a CSV file using Python. I have a CSV file containing a wide table of values. Each row represents an organization and each column contains the value of a different variable.

How can I reshape this data so that each row represents a tuple of (date, orgID, variable, value):

Original shape:

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

Date Org ID A B C D
6/30/2022 04815 10 15 20 30
6/30/2022 01712 4 8 9 14

Desired shape:

Date Org ID Variable Value
6/30/2022 04815 A 10
6/30/2022 04815 B 15
6/30/2022 04815 C 20
6/30/2022 04815 D 30
6/30/2022 01712 A 4
6/30/2022 01712 B 8
6/30/2022 01712 C 9
6/30/2022 01712 D 14

>Solution :

you can use melt:

res = df.melt(id_vars=['Date','Org ID'])

output :

        Date  Org ID variable  value
0  6/30/2022    4815        A     10
1  6/30/2022    1712        A      4
2  6/30/2022    4815        B     15
3  6/30/2022    1712        B      8
4  6/30/2022    4815        C     20
5  6/30/2022    1712        C      9
6  6/30/2022    4815        D     30
7  6/30/2022    1712        D     14
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