Group By without merging python data labels

Asked

Viewed 33 times

0

Hello, people, I have the dataframe below and I need to group and add the columns. For this I am using groupby, but in the result the labels are cancatenated, there is a way that this does not happen?

In the 'codes' column I would like for each row to repeat the code.

import pandas as pd
import numpy as np

codes=['2', '2', '2', '3','3','3', '2', '3']
ano_mes=['201809', '201809', '201809', '201809','201809','201809', '201810', '201810']
produto=['Meal', 'Meal', 'Meal', 'Food', 'Food', 'Food', 'Food', 'Food']
sales=[200,300,400,200,300,300,200, 150]
receita=[2,3,4,2,3,3,2,1.5]


df = pd.DataFrame({'codes': codes,
                   'ano_mes':ano_mes,
                   'produto': produto,
                  'sales': sales,
                  'receita': receita})

df_2 = df.groupby(['codes', 'ano_mes', 'produto']).sum()

inserir a descrição da imagem aqui

1 answer

0


You can "reset" the index by making use of the function reset_index() so that all values are displayed:

...
df_2 = df.groupby(['codes', 'ano_mes','produto']).sum().reset_index().to_string(index=False)

Or (for better viewing):

...
df_2 = df.groupby(['codes', 'ano_mes', 'produto']).sum()
df_2 = df_2.reset_index().to_string(index=False)

Done this, the output of df_2 will stay the way you want:

codes ano_mes produto  sales  receita
    2  201809    Meal    900      9.0
    2  201810    Food    200      2.0
    3  201809    Food    800      8.0
    3  201810    Food    150      1.5

The function reset_index() has as its function "reset" the Dataframe index and use the default index instead.

  • 1

    Perfect, worked out! Super Thanks!

  • Show! If the answer helped you please mark as accepted by clicking there on the affirmative that is next to the voting arrows :)

  • 1

    Done. Thank you!

Browser other questions tagged

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