1

I have a DataFrame as below:

ID     V1  V2  V3  V4  
3261    a   i   k   3  
3262    b   j   l   2  
3263    c       m   4  
3264    d   j   k   5  
3265    e   i       5  

I want to transform this as below, is there a way to do this?

ID  NewHeader1  NewHeader2  
3261    V1  a  
3261    V2  i  
3261    V3  k  
3261    V4  3  
3262    V1  b  
3262    V2  j  
3262    V3  l  
3262    V4  2  
3263    V1  c  
3263    V2    
3263    V3  m  
3263    V4  4  
3264    V1  d  
3264    V2  j  
3264    V3  k  
3264    V4  5  
3265    V1  e  
3265    V2  i  
3265    V3    
3265    V4  5  

Let me know if additional info required.

1
  • Look at stack or unstack. Commented Aug 22, 2016 at 15:01

1 Answer 1

1
pd.melt(df, id_vars ='ID', var_name='NewHeader1', value_name='NewHeader2')
Out: 
      ID NewHeader1 NewHeader2
0   3261         V1          a
1   3262         V1          b
2   3263         V1          c
3   3264         V1          d
4   3265         V1          e
5   3261         V2          i
6   3262         V2          j
7   3263         V2           
8   3264         V2          j
9   3265         V2          i
10  3261         V3          k
11  3262         V3          l
12  3263         V3          m
13  3264         V3          k
14  3265         V3           
15  3261         V4          3
16  3262         V4          2
17  3263         V4          4
18  3264         V4          5
19  3265         V4          5

You can add .sort_values(by='ID') at the end for the sorted version.

pd.melt(df, id_vars ='ID', var_name='NewHeader1', value_name='NewHeader2').sort_values('ID')
Out: 
      ID NewHeader1 NewHeader2
0   3261         V1          a
5   3261         V2          i
10  3261         V3          k
15  3261         V4          3
1   3262         V1          b
6   3262         V2          j
11  3262         V3          l
16  3262         V4          2
2   3263         V1          c
17  3263         V4          4
7   3263         V2           
12  3263         V3          m
3   3264         V1          d
8   3264         V2          j
18  3264         V4          5
13  3264         V3          k
9   3265         V2          i
4   3265         V1          e
14  3265         V3           
19  3265         V4          5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.