PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How can I reshape a wide CSV table using python?

 August 28, 2022     csv, pandas, python     No comments   

Issue

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:

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


Answered By - eshirvana
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing