Home > Back-end >  How to add a a row on a multi index data frame?
How to add a a row on a multi index data frame?

Time:03-09

Ok, so I'm struggling with the following, let's say I have the following table

enter image description here

What I want to do is that on each territorial column I could add a column with the sum per index of territorial, what I want that I could look like this:

enter image description here

It's basically this, to add the rows of totals per index.

CodePudding user response:

You can use:

df.reset_index(inplace=True)
df['EFFECTIVIDAD'] = df['Turno'].div(df['Folio Cita']).mul(100)
df['TERRITORIAL'] = df['TERRITORIAL'].ffill()
df_sum = df.groupby(['TERRITORIAL']).agg({'Folio Cita':'sum', 'Turno':'sum'}).reset_index()
df_sum['EFFECTIVIDAD'] = df_sum['Turno'].div(df_sum['Folio Cita']).mul(100)
df_sum['REGIONAL'] = 'Total '   df_sum['TERRITORIAL']

df = pd.concat([df, df_sum], ignore_index=True).sort_values(by=['TERRITORIAL'])
print(df)
  • Related