简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM