Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - How to melt 2 columns at the same time?

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 melt two columns at once. That is, the desired output is:

   id1 id2 tz  lz  
0  1   2   a   b
1  1   2   c   d
2  3   4   g   h
3  3   4   i   j

I know standard melting:

d.melt(id_vars=['id1', 'id2'],
       value_vars=['t1', 't2', 'l1', 'l2'])

but that stacks all columns

   id1  id2 variable value
0    1    2       t1     a
1    3    4       t1     g
2    1    2       t2     c
3    3    4       t2     i
4    1    2       l1     b
5    3    4       l1     h
6    1    2       l2     d
7    3    4       l2     j

How could I melt two columns at once? Something like:

d.melt(id_vars=['id1', 'id2'],
       value_vars={('t1', 'l1'): 'tz', ('t2', 'l2'): 'lz'})

would be great.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...