Group data by Month/Year

Asked

Viewed 1,539 times

0

import numpy as np
import pandas as pd

BASE_GERAL = pd.read_csv('base_prestadores.csv')

indice | data_utilização| preço  | quantidade_itens
1      | 2014-05-01     | 20.00  |    5
2      | 2014-05-08     | 30.00  |    6
3      | 2014-04-10     | 50.00  |    8
4      | 2014-04-15     | 20.00  |    10

I imported the above table and need to group the data by month/year, considering the sum of the quantity of items how can I do this?

  • In what format do you expect the data to come out? , everything that is the same month will add up the price and quantity of items?

  • I want to assemble a bar graph, considering only the sum of the quantities of the items.

1 answer

0


I made that code. I hope it helps.

import pandas as pd

#garanto que as colunas então com o type certo
df['data_utilizacao'] = df['data_utilizacao'].astype('datetime64')
df['quantidade_itens'] = df['quantidade_itens'].astype('int')

#crio uma coluna mes_ano
df['mes_ano'] = df['data_utilizacao'].map(lambda x: 100*x.year + x.month)

#pego só as colunas que interessam
df = df.ix[:, ['mes_ano', 'quantidade_itens']]

#junto pelo mes_ano igual somando a quantidade_itens
df = df.groupby(['mes_ano']).sum().reset_index()

>>> print(df)
   mes_ano  quantidade_itens
0   201404                18
1   201405                11
  • Thank you very much, it worked!

Browser other questions tagged

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