简体   繁体   中英

python pandas dataframe rename a colume to a multiindex column

I have the following dataframe

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((4,4)))

df
Out[5]: 
          0         1         2         3
0  0.136122  0.948477  0.173869  0.929373
1  0.194699  0.759875  0.723993  0.497966
2  0.323100  0.443267  0.210721  0.681426
3  0.590853  0.710664  0.202502  0.950658

I also have a column mapper:

mapping = {0: ('1', 'A'), 1: ('1', 'B'), 2: ('2', 'A'), 3: ('2', 'B')}

Is there a way to use mapping to rename the column in df to the below? that is change the column to a multiindex by the mapping directly.

          1                   2          
          A         B         A         B
0  0.136122  0.948477  0.173869  0.929373
1  0.194699  0.759875  0.723993  0.497966
2  0.323100  0.443267  0.210721  0.681426
3  0.590853  0.710664  0.202502  0.950658

ps, I know I can simply do the below,

df.columns = pd.MultiIndex.from_product([['1','2'],['A','B']])

Use Index.map , if use pandas 0.23+ is possible omit .get :

df.columns = df.columns.map(mapping.get)
print (df)
          1                   2          
          A         B         A         B
0  0.696469  0.286139  0.226851  0.551315
1  0.719469  0.423106  0.980764  0.684830
2  0.480932  0.392118  0.343178  0.729050
3  0.438572  0.059678  0.398044  0.737995

Another solution with rename , but is necessary convert to MultiIndex in next step:

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