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