如何用日期字符串的一部分在 pandas 中进行groupby? [英] How to do groupby in pandas with part of date string?

查看:74
本文介绍了如何用日期字符串的一部分在 pandas 中进行groupby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        Date Description 
0  6/09/2012      Amazon
1  6/09/2012      iTunes
2  6/08/2012      iTunes
3  6/08/2012    Building
4  6/08/2012   Slicehost

我有一个 DataFrame 像上面那样。我可以使用get_day()这样的函数来挑选上述日期字符串的一天:

I have a DataFrame like the above. I can pick out the day part of the above datestring using a function get_day() like this:

def get_day(date_string):
    d = datetime.strptime(date_string, '%m/%d/%Y')
    return d.day

现在我该如何将这个函数传递给上面的DataFrame来获取groupby的日子,而不是日期字符串本身。无法从查看文档中弄明白。任何帮助赞赏。

Now how do I pass this function to the above DataFrame to get groupby going on the day rather than the datestring itself. Couldn't figure it out from looking at the docs. Any help appreciated.

推荐答案

df.groupby(get_day)

但是我会首先将日期字符串转换为datetime对象。

but I would convert the date strings to datetime objects first anyway.

另一个问题是你打电话给 .day ,它返回一个月中的一天(1-31)。您可能想要调用 .date()

Another problem is that you're calling .day which returns a day of month (number 1-31). You probably want to call .date():

def get_day(date_string):
    return datetime.strptime(date_string, '%m/%d/%Y').date()

或直接

or directly

df.groupby(lambda x: datetime.strptime(date_string, '%m/%d/%Y').date())

这篇关于如何用日期字符串的一部分在 pandas 中进行groupby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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