Reputation: 785
I have a pandas dataframe with a column of 'date_created'
the column has a following format of YYYY-MM-DD. for example: 2017-10-05
I want to group it by MM/YYYY
I used this but it included DD
frame['date_created'].value_counts()
is there anyway to query it by using YYYY and MM
Upvotes: 2
Views: 7128
Reputation: 59274
You can also group by month and count
over
frame.set_index("date_created").groupby(pd.Grouper(freq='M')).count()
Upvotes: 4
Reputation: 164633
I would create a new column, say "YearMonth" with day fixed to 1. Then group by this column:
import pandas as pd
df = pd.DataFrame({'Date': ['2017-10-05', '2017-10-20']})
df['YearMonth'] = pd.to_datetime(df['Date']).map(lambda dt: dt.replace(day=1))
res = df['YearMonth'].value_counts()
# 2017-10-01 2
# Name: YearMonth, dtype: int64
Upvotes: 5