Reputation: 3789
I have created a dataframe as below:
paystart = datetime.date(2017, 10, 26)
paydate = pd.DataFrame()
paydate['PayDate'] = pd.date_range(paystart, end, freq='14D')
print(paydate.Grouper(freq='M'))
I want to count the number instances of date for any month-year combination i.e. Result should look like:
2017-10 1
2017-11 2
2017-12 2
Upvotes: 1
Views: 47
Reputation: 862581
If use Grouper
with GroupBy.size
or DataFrame.resample
with Resampler.size
output is DatetimeIndex
:
paydate = pd.DataFrame()
paydate['PayDate'] = pd.date_range('2017-10-26', '2017-12-26', freq='14D')
print (paydate)
PayDate
0 2017-10-26
1 2017-11-09
2 2017-11-23
3 2017-12-07
4 2017-12-21
print(paydate.groupby(pd.Grouper(freq='M', key='PayDate')).size())
PayDate
2017-10-31 1
2017-11-30 2
2017-12-31 2
Freq: M, dtype: int64
print(paydate.resample('M', on='PayDate').size())
PayDate
2017-10-31 1
2017-11-30 2
2017-12-31 2
Freq: M, dtype: int64
Or is possible create month periods by Series.dt.to_period
- output is PeriodIndex
:
print(paydate.groupby(paydate['PayDate'].dt.to_period('m')).size())
PayDate
2017-10 1
2017-11 2
2017-12 2
Freq: M, dtype: int64
Upvotes: 1