I'm trying to convert a dataframe in Python, and I am stuck because I don't know exactly how to phrase what I want to do (which makes searching for it difficult). It seems like I need a combination of unstack and pivot. I can explain it with an example though, hopefully. I have a dataframe with this shape:
userid | GroupA_measure1 | GroupA_measure2 | GroupB_measure1 | GroupB_measure2 |
---|---|---|---|---|
001 | 65 | 70 | 45 | 50 |
002 | 96 | 89 | 12 | 8 |
003 | 12 | 14 | 38 | 40 |
and I want to convert this to this format:
userid | measure | groupA | groupB |
---|---|---|---|
001 | 1 | 65 | 45 |
001 | 2 | 70 | 50 |
002 | 1 | 96 | 12 |
002 | 2 | 89 | 8 |
003 | 1 | 12 | 38 |
003 | 2 | 14 | 40 |
I can unstack the whole df using pd.melt(df, id_vars =['userid'])
which put all values in separate rows, but I want to keep separate columns for the values of GroupA and GroupB.
Any help would be much appreciated.