0

I have a dataset like this

A    B    C D
Cat Meow  1 2
Dog Grr   3 4

I need to convert into the bwlow format by creating new columns

Level Focus C D
A     Cat   1 2
A     Dog   3 4
B     Meow  1 2
B     Grr   3 4

I am not sure how I can achieve this using pivot_table()

2 Answers2

2

Try using melt:

df.melt(['C', 'D'], var_name='Level', value_name='Focus')

Output:

   C  D Level Focus
0  1  2     A   Cat
1  3  4     A   Dog
2  1  2     B  Meow
3  3  4     B   Grr

Another way for pedagogical reasons:

df.set_index(['C', 'D']).stack().reset_index().rename(columns={'level_2':'Level',0:'Focus'})

Output:

   C  D Level Focus
0  1  2     A   Cat
1  1  2     B  Meow
2  3  4     A   Dog
3  3  4     B   Grr
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

Use melt and the rename columns according to your desire result.

df = df.melt(['C', 'D'])
df=df.rename(columns = {'variable':'Level', 'value':'Focus'}, inplace = True)
Umer Rana
  • 148
  • 6
  • Check out the parameters in `melt`, `var_name` and `value_name`. And, you cannot use `inplace=True` with reassign back to variable df. Inplace=True returns null. – Scott Boston Jun 25 '20 at 12:58
  • You edited your answer after viewing my answer. But I did it with different approach not like yours. – Umer Rana Jun 25 '20 at 13:01