How to melt 2 columns at the same time?

后端 未结 2 1744
遇见更好的自我
遇见更好的自我 2020-11-27 23:16

In Pandas, I have the following data frame:

   id1 id2 t1  l1  t2  l2 
0  1   2   a   b   c   d
1  3   4   g   h   i   j

I would like to me

相关标签:
2条回答
  • 2020-11-27 23:25

    You can use melt twice here and after that concat them to get desired output:

    t = d.melt(id_vars=['id1', 'id2'], value_vars=['t1', 't2'], value_name='tz').drop('variable', axis=1)
    l = d.melt(id_vars=['id1', 'id2'], value_vars=['l1', 'l2'], value_name='lz').iloc[:, -1:]
    
    df = pd.concat([t, l], axis=1).sort_values('id1')
    

    Output

    print(df)
       id1  id2 tz lz
    0    1    2  a  b
    2    1    2  c  d
    1    3    4  g  h
    3    3    4  i  j
    
    0 讨论(0)
  • 2020-11-27 23:44

    This is wide_to_long

    pd.wide_to_long(df,['t','l'],i=['id1','id2'],j='drop').reset_index(level=[0,1])
    Out[52]: 
          id1  id2  t  l
    drop                
    1       1    2  a  b
    2       1    2  c  d
    1       3    4  g  h
    2       3    4  i  j
    
    0 讨论(0)
提交回复
热议问题