Python – Converts a Pandas data frame to another layout

Converts a Pandas data frame to another layout… here is a solution to the problem.

Converts a Pandas data frame to another layout

I have a data frame like this:

  column1  column2  column3
0       A    0.020     0.76
1       B    0.045     1.30
2       C    0.230     0.32
3       D    0.130     0.67

I want to modify this dataframe structure so that it looks like this :

column1  newCol 
A        column2    0.020
         column3    0.760
B        column2    0.045
         column3    1.300
C        column2    0.230
         column3    0.320
D        column2    0.130
         column3    0.670
Name: value, dtype: float64

where column1, column2, column3, newCol are the names of the columns
A, B, C, D are unique values for rows

My problem is that I don’t know how to convert column1 and column2 from columns to rows in a new data frame.

Solution

Set column1 as index, stack, rename index column:

>>> res = df.set_index('column1').stack()
>>> res.index.names = ['column1', 'newCol']
>>> res

column1  newCol 
A        column2    0.020
         column3    0.760
B        column2    0.045
         column3    1.300
C        column2    0.230
         column3    0.320
D        column2    0.130
         column3    0.670
dtype: float64

Related Problems and Solutions