pandas 数据框 groupby datetime 月份 [英] pandas dataframe groupby datetime month

查看:65
本文介绍了pandas 数据框 groupby datetime 月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个 csv 文件:

Consider a csv file:

string,date,number
a string,2/5/11 9:16am,1.0
a string,3/5/11 10:44pm,2.0
a string,4/22/11 12:07pm,3.0
a string,4/22/11 12:10pm,4.0
a string,4/29/11 11:59am,1.0
a string,5/2/11 1:41pm,2.0
a string,5/2/11 2:02pm,3.0
a string,5/2/11 2:56pm,4.0
a string,5/2/11 3:00pm,5.0
a string,5/2/14 3:02pm,6.0
a string,5/2/14 3:18pm,7.0

我可以读入,并将日期列重新格式化为日期时间格式:

I can read this in, and reformat the date column into datetime format:

b=pd.read_csv('b.dat')
b['date']=pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')

我一直在尝试按月对数据进行分组.似乎应该有一种明显的方式来访问月份并按月份分组.但我似乎做不到.有人知道怎么做吗?

I have been trying to group the data by month. It seems like there should be an obvious way of accessing the month and grouping by that. But I can't seem to do it. Does anyone know how?

我目前正在尝试按日期重新索引:

What I am currently trying is re-indexing by the date:

b.index=b['date']

我可以这样访问月份:

b.index.month

但是我似乎无法找到按月汇总的功能.

However I can't seem to find a function to lump together by month.

推荐答案

设法做到了:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

或者

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+

这篇关于pandas 数据框 groupby datetime 月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆