Chiou Chiou Aymen
Chiou Chiou Aymen

Reputation: 23

How can I rotate a pandas.dataframe using colmun names

I have the following DataFrame, with Timestamp as the index:

Timestamp 40_x 40_y 40_z 60_x 60_y 60_z 80_x 80_y 80_z
    10:00    a    b    c    d    e    f    g    h    i
    10:10   a2   b2   c2   d2   e2   f2   g2   h2   i2

I want to rotate it into the following DataFrame:

                  x   y   z
Timestamp range               
10:00        40   a   b   c
10:00        60   d   e   f
10:00        80   g   h   i
10:10        40  a2  b2  c2
10:10        60  d2  e2  f2
10:10        80  g2  h2  i2

I have a list of ranges: [40, 60, 80], and it can contain many more values.

Upvotes: 2

Views: 111

Answers (1)

Umar.H
Umar.H

Reputation: 23099

How about a MultiIndex then stack?

df.columns = df.columns.str.split('_',expand=True)

print(df)

           40          60          80        
            x   y   z   x   y   z   x   y   z
Timestamp                                    
10:00       a   b   c   d   e   f   g   h   i
10:10      a2  b2  c2  d2  e2  f2  g2  h2  i2

df1 = df.stack(0)

print(df1)

               x   y   z
Timestamp               
10:00     40   a   b   c
          60   d   e   f
          80   g   h   i
10:10     40  a2  b2  c2
          60  d2  e2  f2
          80  g2  h2  i2

Upvotes: 5

Related Questions