Pandas - Exhibition after groupby

Asked

Viewed 31 times

-2

How do I make sure the Offices column does not go blank, thus repeating the office name?

mun_df = planta_df[['Empresas', 'Escritórios', 'Municípios', 'Estados']]
mun_df = mun_df.groupby(['Empresas', 'Escritórios', 'Municípios']).count()
mun_df = mun_df.rename(columns={'Estados': 'Acessos'})

mun_df.to_excel('Disponibilidade.xlsx', sheet_name='Municípios')

inserir a descrição da imagem aqui

  • Could you please share a little more of the code? Like the planta_df is structured, what data is in it?

1 answer

1

The reset_index() is your friend in this case. See the example below:

Creating Test Dataframe

>>> import pandas as pd

>>> df = pd.DataFrame({"Escritorios": ["A", "A","A","A","A"], "Municipios": ["Aruja", "Poa", "Poa", "Aruja", "Poa"], "Acessos": [1, 2, 2, 1, 2]})

>>> df
  Escritorios Municipios  Acessos
0           A      Aruja        1
1           A        Poa        2
2           A        Poa        2
3           A      Aruja        1
4           A        Poa        2

Grouping data

>>> df.groupby(["Escritorios", "Municipios"])["Acessos"].sum()

Escritorios  Municipios
A            Aruja         2
             Poa           6
Name: Acessos, dtype: int64

Grouping data and using reset_index()

>>> df.groupby(["Escritorios", "Municipios"])["Acessos"].sum().reset_index()

  Escritorios Municipios  Acessos
0           A      Aruja        2
1           A        Poa        6

That is, just assign to a new dataframe and save to Excel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.