Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add another subcolumn to dataframe with multi-index

I’m trying to add a third column "Productivity" so every role like Admin would have three sub columns produktiv, unproduktiv and Productivity.

Productivity would be calculated as follows:

Productivity = Produktiv / (Produktiv + Unproduktiv) * 100

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dataframe
(don’t mind the s, I had to anonymize the data)

Here is the output of df.columns

enter image description here

Any help would be greatly appreciated. Thank you.

>Solution :

If there are only Produktiv and Unproduktiv level for sum is possible aggregate by first level of MultiIndex, divide by Produktiv and after rename second level of MultiIndex append to originam Dataframe by concat:

df1 = (df.xs('Produktiv', axis=1, level=1, drop_level=False)
         .div(df.groupby(level=0, axis=1).sum(), level=0).mul(100))

df = (pd.concat([df, df1.rename(columns={'Produktiv':'Productivity'}, level=1)], axis=1)
        .sort_index(axis=1)
        .reindex(['Produktiv','Unproduktiv','Productivity'], level=1, axis=1))
print (df)

Another idea is get both slices by Produktiv, Unproduktiv and add level by pd.concat first:

df1 = df.xs('Produktiv', axis=1, level=1)
df2 = df.xs('Unproduktiv', axis=1, level=1)

df11 = (pd.concat({'Productivity':df1.div(df1.add(df2)).mul(100)}, axis=1)
          .swaplevel(0,1,axis=1))
    
df = (pd.concat([df, df11], axis=1)
        .sort_index(axis=1)
        .reindex(['Produktiv','Unproduktiv','Productivity'], level=1, axis=1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading