Martin Böschen
Martin Böschen

Reputation: 1769

How to generate a bar chart of occurrences per month from a pandas Series?

I have a pandas Series which looks like this:

id
368683    2012-01-01 01:20:08
77642     2012-01-01 03:18:40
335652    2012-01-01 03:39:48

...
188283    2013-04-30 23:22:33
137637    2013-04-30 23:25:40
Name: created_time, Length: 223129

Now I want to create a bar chart, where I list the occurrences per month? What would be the pandas way to do that?

Upvotes: 1

Views: 2613

Answers (2)

Martin Böschen
Martin Böschen

Reputation: 1769

Thanks for the help so far. I ended up with the following code:

frame2 = DataFrame.from_csv("data/test.csv")
times2 = frame2['created_time']
m = times2.apply(lambda x: dateutil.parser.parse(x).strftime('%Y-%m'))
x=m.value_counts()
x=x.sort_index()
x.plot(kind='bar')
plt.show()

This produces the following plot: enter image description here

Upvotes: 1

roman
roman

Reputation: 117380

Looks like you need histogram() of months. I think it could be done by creating another Series with months of given datetimes and then plot it:

m = s.apply(lambda x: x.month)
m.hist()

If you want to get your data in form like 'Jan 2011', ..., you can convert it like this

m = s.apply(lambda x: x.strftime('%b %Y'))

Upvotes: 1

Related Questions