jason
jason

Reputation: 3512

How to do groupby in pandas with part of date string?

        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

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

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.

Upvotes: 3

Views: 2691

Answers (1)

eumiro
eumiro

Reputation: 212835

df.groupby(get_day)

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

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())

Upvotes: 2

Related Questions