0

I have this dataframe:

no   id    type   xa   xa    01   02
1    bar    any   2    3     1     3
2    foo    all   3    4     0     1

the columns I need to transform is coming after the type column, and I actually have plenty of them coming after the type column and the column type is in the form of string and also integer.

so I need to transform any column coming after type to be in dedicated columns which are category and values, and the expected result will be as follow:

no   id   type   category   values
1    bar  any      xa          2
1    bar  any      xa          3
1    bar  any      xa          1
1    bar  any      xa          3
2    foo  all      01          3
2    foo  all      01          4
2    foo  all      01          0
2    foo  all      01          1

I probably can use df.melt, but I am still not sure on how to use it in my case.

How do I suppose to write my script so that I can get my desired dataframe?

Thanks in advance.

nomnom3214
  • 227
  • 1
  • 11

1 Answers1

2

Try this with df.melt:

>>> df = df.melt(['no','id','type'], var_name='category', value_name='values')
   no   id type category values
0   1  bar  any       xa      2
1   2  foo  all       xa      3
2   1  bar  any       xa      3
3   2  foo  all       xa      4
4   1  bar  any       01      1
5   2  foo  all       01      0
6   1  bar  any       02      3
7   2  foo  all       02      1
>>> 
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
U13-Forward
  • 69,221
  • 14
  • 89
  • 114