Home > Mobile >  Pandas - How do you iterate over cols and move them into a new position whilst matching them to rows
Pandas - How do you iterate over cols and move them into a new position whilst matching them to rows

Time:01-14

I have a dataset similar to the one below:

tag1 Desc 07/07/23 14/07/23
TVG text1 153 35
UGY text2 5 88
EXT text3 46 46

My aim is to have the end result be:

tag1 Desc Value Date
TVG text1 153 07/07/23
TVG text1 35 14/07/23
UGY text2 5 07/07/23
UGY text2 88 14/07/23
EXT text3 46 07/07/23
EXT text3 46 14/07/23

I having a hard time accurately describing what I want to do verbally, but effectively I want to tie the date values and their values to the rows based on the tag and the description. I will add more detail and clarity as I am able, but any assistance would be greatly appreciated.

CodePudding user response:

You can use .melt():

df.melt(["tag1", "Desc"], var_name="Date", value_name="Value")

This outputs:

   tag1    Desc      Date Value
0  TVG   text1   07/07/23  153
1  UGY   text2   07/07/23    5
2  EXT   text3   07/07/23   46
3  TVG   text1   14/07/23   35
4  UGY   text2   14/07/23   88
5  EXT   text3   14/07/23   46
  • Related