0

I have a dataframe with the following structure:

Name Value_1 Value_2
John 20 30
Barry 5 10

and i would like something as:

Name Index Value
John Value_1 20
John Value_2 30
Barry Value_1 5
Barry Value_2 10

Does pandas have any method in order to make this transformation ?

Thanks in advance!!

2 Answers2

1

Try:

import pandas as pd

df = pd.DataFrame({'Name': ['John', 'Barry'], 'Value_1': [20, 5], 'Value_2': [30, 10]})

df.melt(id_vars='Name', value_vars=['Value_1', 'Value_2'], var_name='1', value_name='2')

Outputs:

    Name    1         2
0   John    Value_1   20
1   Barry   Value_1   5
2   John    Value_2   30
3   Barry   Value_2   10
MDR
  • 2,610
  • 1
  • 8
  • 18
0

Here is another way:

(df.set_index('Name')
 .rename_axis('Index',axis=1)
 .stack()
 .rename('Value')
 .reset_index())
rhug123
  • 7,893
  • 1
  • 9
  • 24