0

How can I transform a Dataframe with columns S (start), E (end), V (value)

S E V 
1 2 3
2 5 11
5 11 5

And transform it to:

T V
1 3
2 3
2 11
5 11
5 5
11 5

?

This is so that we can plot the data with in such a way the value V (y-axis) is the same throughout the interval.

Edit:

Some are suggesting this is the same as a "how do I use melt()?" question. However the order of the result is important.

Frank Wilson
  • 3,192
  • 1
  • 20
  • 29
  • `df.melt(id_vars='V', value_name='T')[['T', 'V']]` – Henry Ecker Jun 28 '21 at 15:13
  • The trouble with melt is that the order is important. To use melt it seems I need to first create a column from the index so that I resort by row id after melting. It seems that @Nk03 is better since with melt I seem to have to faff with indexes anyway. – Frank Wilson Jun 28 '21 at 15:47

2 Answers2

1

Or with set_index/stack:

df = df.set_index('V').stack().reset_index(-1, drop =True).reset_index(name = 'T')

OUTPUT:

    V   T
0   3   1
1   3   2
2  11   2
3  11   5
4   5   5
5   5  11
Nk03
  • 14,699
  • 2
  • 8
  • 22
0

Try with melt

df.melt('V')
Out[39]: 
    V variable  value
0   3        S      1
1  11        S      2
2   5        S      5
3   3        E      2
4  11        E      5
5   5        E     11
BENY
  • 317,841
  • 20
  • 164
  • 234
  • The order of the result is important. The best I can do is with melt is: df.rename_axis('ix').reset_index().melt(['V','ix'], value_name='T').sort_values(['ix','variable'], ascending=[True, False]) – Frank Wilson Jun 28 '21 at 15:56