简体   繁体   English

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

[英]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. Python 3,熊猫 1.1.1。

Use DataFrame.unstack by both levels:在两个级别使用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

Another idea with DataFrame.stack , but is necessary some another processing - Series.reorder_levels and Series.sort_index : 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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