1

I have pandas that looks at follows:

df = id       A_value       D_value
      1        50            60
      2        33            45

And I want to split it to:

df = id       value       value_type
      1        50           A
      1        60           D 
      2        33           A
      2        45           D

What is the best way to do so?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Cranjis
  • 1,590
  • 8
  • 31
  • 64

1 Answers1

0

You can try:

>>> df1 = pd.melt(df, id_vars=['id'], var_name='value_type')
>>> df1
   id value_type  value
0   1    A_value     50
1   2    A_value     33
2   1    D_value     60
3   2    D_value     45

>>> df1.value_type = df1.value_type.str.extract(r'(\w)_')
>>> df1
   id value_type  value
0   1          A     50
1   2          A     33
2   1          D     60
3   2          D     45
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
abhilb
  • 5,639
  • 2
  • 20
  • 26