0

Greetings of the day!!

I have a pandas Dataframe like below:

A 2022-Mar 2022-Apr
1 111 222
2 333 444

I am expecting resultant dataframe like below:

A MonthYear Quantity
1 2022-Mar 111
1 2022-Apr 222
2 2022-Mar 333
2 2022-Apr 444

Please help me with this!

I can achieve this using Pandas Stack method, but i have to do this using Pandas pivot method.

Note: In resultant table i have to create column names as well.

Thanks in advance!

I have tried pandas stack method and i have achieved this... But my requirement is like to do with pandas pivot method.

Tried method:

newDF = df.set_index('A') .stack().rename(columns{'level_1':'MonthYear',0:'Quantity'})

display(newDF)

Kr7sh
  • 1
  • It is unpivot, so need `melt`, not `pivot` – jezrael Mar 28 '22 at 07:25
  • Hey @jezrael, Thanks for this solution... It seems good but i am not getting the desired output... It is giving me the result like |A| --> 1 2 1 2, but i need like 1 1 2 2. So what should be done? Could you help? I have tried so many methods to sort but didn't help. – Kr7sh Mar 28 '22 at 08:57
  • If dont want use `stack` use`melt` with `sort_values(['A'])` – jezrael Mar 28 '22 at 08:58

0 Answers0