Skip to content Skip to sidebar Skip to footer

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 des

Solution 1:

This is wide_to_long

pd.wide_to_long(df,['t','l'],i=['id1','id2'],j='drop').reset_index(level=[0,1])
Out[52]: 
      id1id2tldrop112ab212cd134gh234ij

Solution 2:

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
012ab212  c  d
134  g  h
334i  j

Post a Comment for "How To Melt 2 Columns At The Same Time?"