简体   繁体   中英

Convert indexed DataFrame to multi-indexed using pattern in indices

I have the DataFrame with the following structure (ie indices has some lexical intersections):

        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):

        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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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