Shurlena
Shurlena

Reputation: 21

Rearrange columns in DataFrame

Having a DataFrame structured as follows:

    country       A      B        C      D  
0   Albany       5.2    4.7     253.75   4
1   China        7.5    3.4     280.72   3
2   Portugal     4.6    7.5     320.00   6
3   France       8.4    3.6     144.00   3
4   Greece       2.1    10.0    331.00   6

I wanted to get something like this:

cost             A            B
country       C     D     C      D
Albany      2.05    4    1.85    4
China       2.67    3    1.21    3
Portugal    1.44    6    2.34    6
France      5.83    3    2.50    3
Greece      0.63    6    3.02    6

I mean, get the columns A and B as headers over C and D, keeping D the same with its constant value, and calculating in C the percentage resulting of the header over C. Example for Albany:

Is there any way to do it?

Thanks!

Upvotes: 0

Views: 67

Answers (1)

jezrael
jezrael

Reputation: 862511

You can divide multiple columns, here A and B by DataFrame.div, then DataFrame.reindex by MultiIndex created by MultiIndex.from_product and last set D columns by original with MultiIndex slicers:

cols = ['A','B']
mux = pd.MultiIndex.from_product([cols, ['C', 'D']])
df1 = df[cols].div(df['C'], axis=0).mul(100).reindex(mux, axis=1, level=0)

idx = pd.IndexSlice
df1.loc[:, idx[:, 'D']] = df[['D'] * len(cols)].to_numpy()
#pandas bellow 0.24
#df1.loc[:, idx[:, 'D']] = df[['D'] * len(cols)].values
print (df1)
          A            B   
          C  D         C  D
0  2.049261  4  1.852217  4
1  2.671701  3  1.211171  3
2  1.437500  6  2.343750  6
3  5.833333  3  2.500000  3
4  0.634441  6  3.021148  6

Upvotes: 3

Related Questions