0

I have a following dataframe

multicol = pd.MultiIndex.from_arrays([['1','1','2','2','2'],
           ['A','B','A','B','C']], names=('Num','Base'))
df = pd.DataFrame([[1,2,3,4,5],[2,1,2,3,4],[3,2,1,2,3],
     [4,3,2,1,2],[5,4,3,2,1]], index=multicol, columns=multicol)

enter image description here

I want to reshape it to be like this

| Num | Base | Base | Value |
+-----+------+------+-------+
|(1,1)|   A  |   A  |   1   |
+-----+------+------+-------+
|(1,1)|   A  |   B  |   2   |
+-----+------+------+-------+
|(1,1)|   B  |   A  |   2   |
+-----+------+------+-------+
|(1,1)|   B  |   B  |   1   |
+-----+------+------+-------+
|(1,2)|   A  |   A  |   3   |
+-----+------+------+-------+
    .....................

    .....................
|(2,2)|   C  |   C  |   1   |
+-----+------+------+-------+

I have tried to use stack(), but the new order is Num | Base | Base | Num | value |. How to achieve a new dataframe with a result likes the one I expected?

Thank you.

Tobi
  • 171
  • 8
  • kindly share the source data, not pics. just a couple of rows. – sammywemmy Feb 21 '21 at 23:20
  • 1
    Does this answer your question? [Reorder levels of MultiIndex in a pandas DataFrame](https://stackoverflow.com/questions/34029608/reorder-levels-of-multiindex-in-a-pandas-dataframe) – Michael Delgado Feb 22 '21 at 01:02
  • @MichaelDelgado Yes and No. I need the row is ordered by index too, but I found function `sort_index()` and now I got what I want. Thanks :) – Tobi Feb 22 '21 at 01:18

0 Answers0