5

I have the following dataframe that I try to 'melt'.

enter image description here

So my aim is to get a output with 2 column

  • Column name
  • Value

So my output should look like [that's only the head of the output, I don't show it fully to be concise]

enter image description here

I have tried the following but it not works.

df2 = pd.melt(df, id_vars=df.index, var_name="Name", value_name="Value")

It says: KeyError: "The following 'id_vars' are not present in the DataFrame:

PS: The columns are 'predictors' so if not too complicated I would be happy to add a P as prexix in the column name like P0 P1 P2 P3 P4 P5

enter image description here

S12000
  • 3,345
  • 12
  • 35
  • 51

1 Answers1

6

We can just adding the reset_index

pd.melt(df.reset_index(), id_vars='index', var_name="Name", value_name="Value") 

Or using stack

df.stack().reset_index()
BENY
  • 317,841
  • 20
  • 164
  • 234
  • 1
    Note that if your index happens to have a name, you'll have to use that instead of `'index'`. – adr Mar 13 '20 at 14:19