I extracted dates and times from a string and converted them to the Pandas DatFrame, by wrintig:
df = pd.to_datetime(news_date, format='%m/%d/%Y')
and the output is like:
['1997-10-31 18:00:00', '1997-10-31 18:00:00',
'1997-10-31 18:00:00', '1997-10-31 18:00:00',
'1997-10-31 18:00:00', '1997-10-31 18:00:00',
'1997-10-31 18:00:00', '1997-10-31 18:00:00',
'1997-10-31 18:00:00', '1997-10-31 18:00:00',
...
'2016-12-07 03:14:00', '2016-12-09 16:31:00',
'2016-12-10 19:02:00', '2016-12-11 09:41:00',
'2016-12-12 05:01:00', '2016-12-12 05:39:00',
'2016-12-12 06:44:00', '2016-12-12 08:11:00',
'2016-12-12 09:36:00', '2016-12-12 10:19:00']
Then I wanted to keep only month and year and sort the date, I wrote:
month_year = df.to_series().apply(lambda x: dt.datetime.strftime(x, '%m-%Y')).tolist() # remove time and day
new = sorted(month_year, key=lambda x: datetime.datetime.strptime(x, '%m-%Y')) # sort date
so far, I have a list of dates. The problem occurs when I try to count the frequency of them (I have to plot time-distribution later on). My code is :
print(pd.DataFrame(new).groupby(month_year).count())
and the output is:
01-1998 60
01-1999 18
01-2000 49
01-2001 50
01-2002 87
01-2003 129
01-2004 125
01-2005 225
01-2006 154
01-2007 302
01-2008 161
01-2009 161
01-2010 167
01-2011 181
01-2012 227
... ...
12-2014 82
12-2015 89
12-2016 13
Nevertheless, I want to have a sorted date in one column, and its frequency in the other column(e.g., Pandas DataFrame) that can be plotted easily, like:
01-1998 60
02-1998 32
03-1998 22
... ...
11-2016 20
12-2016 13