Reputation: 832
I have a pd.DataFrame
where I want to convert some columns into rows. I have the example below where I have 2 different sample with multiple target measurements. I want to break the targets ['t1', 't2', 't3']
and split them into new target row with the sample number. Is there a better way than a for-loop to convert a series of values (in columns) into rows ?
#The entry I have:
pd.DataFrame({'Sample':[0,1],
't1':[2,3],
't2':[4,5],
't3':[6,7]})
# the output I'm expecting:
pd.DataFrame({'Sample':[0,0,0,1,1,1],
'targets':[2,4,6,3,5,7]})
I don't think that the pd.pivot_table()
can do that for me.
Does anyone have an idea ?
Upvotes: 1
Views: 74
Reputation: 323226
You are looking for melt
pd.DataFrame({'Sample':[0,1],
't1':[2,3],
't2':[4,5],
't3':[6,7]}).melt('Sample')
Out[74]:
Sample variable value
0 0 t1 2
1 1 t1 3
2 0 t2 4
3 1 t2 5
4 0 t3 6
5 1 t3 7
Upvotes: 1