1

I am trying to use pandas.melt() or pandas.pivot() to convert rows from Column Food-Type into Column headings and Dates into row.

Food-Type  2021 Oct-21   Nov-21
Banana      104  104.4   105.5
cereals    105.7  105.8  106.5
Rice       97.6   97.5   98.2

The end result should be like this.

         Banana  cereals   Rice
 2021    104      105.7    105.5
 Oct-21  104.4    105.8    106.5
 Nov-21  105.5    97.5     98.2
Sam
  • 21
  • 2

1 Answers1

1

Use a transposition, after setting Food-Type as index:

out = df.set_index('Food-Type').T

Output:

Food-Type  Banana  cereals  Rice
2021        104.0    105.7  97.6
Oct-21      104.4    105.8  97.5
Nov-21      105.5    106.5  98.2

Alternative:

out = df.set_index('Food-Type').T.rename_axis(columns=None)

Output:

        Banana  cereals  Rice
2021     104.0    105.7  97.6
Oct-21   104.4    105.8  97.5
Nov-21   105.5    106.5  98.2
mozway
  • 194,879
  • 13
  • 39
  • 75