I apologise for the title, I know it isn’t the most helpful. What I’m attempting to do is restructure my data so that each of a given column is given it’s own row with certain values carried over from the previous dataframe.
My Data in its current form is something like this:
JavaScript
x
4
1
ColA | ColB | ColC | val1 | val2 | val3
2
1 | 2 | 3 | A | B | C
3
4 | 5 | 6 | D | E | F
4
And I want to restructure it so I get a result like this:
JavaScript
1
8
1
ColA | ColB | ColC | val
2
1 | 2 | 3 | A
3
1 | 2 | 3 | B
4
1 | 2 | 3 | C
5
4 | 5 | 6 | D
6
4 | 5 | 6 | E
7
4 | 5 | 6 | F
8
How would I do this?
I know I could go through each row, grab the relevant data and concat a dataframe but I was hoping for a much better alternative
Advertisement
Answer
Given:
JavaScript
1
4
1
ColA ColB ColC val1 val2 val3
2
0 1 2 3 A B C
3
1 4 5 6 D E F
4
Doing:
JavaScript
1
2
1
df.melt(['ColA', 'ColB', 'ColC'])
2
Output:
JavaScript
1
8
1
ColA ColB ColC variable value
2
0 1 2 3 val1 A
3
1 4 5 6 val1 D
4
2 1 2 3 val2 B
5
3 4 5 6 val2 E
6
4 1 2 3 val3 C
7
5 4 5 6 val3 F
8