簡體   English   中英

使用索引中的模式將索引的DataFrame轉換為多索引

[英]Convert indexed DataFrame to multi-indexed using pattern in indices

我的DataFrame具有以下結構(即索引具有一些詞法交集):

        a         b     
        bar  foo  bah  foo
A1B1     1    0    3    2
A1B2     5    4    7    6
A2B1     9    8   11   10
A2B2    13   12   15   14

我希望將此DataFrame轉換為此(即使用某些正則表達式從索引中創建多索引):

        a         b     
        bar  foo  bah  foo
A1  B1   1    0    3    2
    B2   5    4    7    6
A2  B1   9    8   11   10
    B2  13   12   15   14

我可能只會使用map:

In [11]: df.index = pd.MultiIndex.from_tuples(df.index.map(lambda x: (x[0:2], x[2:4])))

In [12]: df
Out[12]:
        a       b
      bar foo bah foo
A1 B1   1   0   3   2
   B2   5   4   7   6
A2 B1   9   8  11  10
   B2  13  12  15  14

您可以使用正則表達式或任何其他形式,只要傳遞給map的函數接受每個項目並返回一個元組即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM