简体   繁体   中英

Convert a two-column dataframe into a multi-indexed series

How do I turn this dataframe:

In [1]: df
Out[1]:
col_name         C    P
FULL  count_x    1    5
      count_y    2    6
CALIB count_x    3    7
      count_y    4    8

into this series:

In [2]: s
Out[2]:    
C  FULL  count_x    1
         count_y    2
   CALIB count_x    3
         count_y    4
P  FULL  count_x    5
         count_y    6
   CALIB count_x    7
         count_y    8

Python 3, Pandas 1.1.1.

Use DataFrame.unstack by both levels:

s = df.unstack([0,1])
print (s)
C  FULL      count_x    1
             count_y    2
   CALIB     count_x    3
             count_y    4
P  FULL      count_x    5
             count_y    6
   CALIB     count_x    7
             count_y    8
dtype: int64

Another idea with DataFrame.stack , but is necessary some another processing - Series.reorder_levels and Series.sort_index :

s = df.stack().reorder_levels([2,0,1]).sort_index()
print (s)
   col_name         
C  CALIB     count_x    3
             count_y    4
   FULL      count_x    1
             count_y    2
P  CALIB     count_x    7
             count_y    8
   FULL      count_x    5
             count_y    6
dtype: int64

Try something new

out = pd.concat({x : df[x] for x in df.columns})
Out[113]: 
   col_name  col_name1
C  FULL      count_x      1
             count_y      2
   CALIB     count_x      3
             count_y      4
P  FULL      count_x      5
             count_y      6
   CALIB     count_x      7
             count_y      8
dtype: int64

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