How can I convert yearly data columns into to yearly data rows based in ID - Pandas Python [duplicate]
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
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