2

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']])

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.