簡體   English   中英

將兩列數據框轉換為多索引系列

[英]Convert a two-column dataframe into a multi-indexed 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,熊貓 1.1.1。

在兩個級別使用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

嘗試新的

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