将两列数据框转换为多索引序列

时间:2020-10-16 13:23:24

标签: python pandas dataframe series

如何打开此数据框:

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

进入本系列:

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

2 个答案:

答案 0 :(得分:4)

在两个级别上都使用DataFrame.unstack

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

关于DataFrame.stack的另一种想法,但有必要进行另一种处理-Series.reorder_levelsSeries.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

答案 1 :(得分:0)

尝试新事物

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