简体   繁体   English

使用索引中的模式将索引的DataFrame转换为多索引

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

I have the DataFrame with the following structure (ie indices has some lexical intersections): 我的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

I want this DataFrame to be converted into this (ie multi-index from index using some regular expression): 我希望将此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

I would probably just use map: 我可能只会使用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

You can use regex, or whatever, provided the function you pass to map takes each item and returns a tuple. 您可以使用正则表达式或任何其他形式,只要传递给map的函数接受每个项目并返回一个元组即可。

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

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