Search code examples
pythonpandasdataframedatetimegroup-by

Python Pandas Group by date using datetime data


I have a datetime column Date_Time that I wish to groupby without creating a new column. Is this possible? I tried the following and it does not work.

df = pd.groupby(df,by=[df['Date_Time'].date()])

Solution

  • resample

    df.resample('D', on='Date_Time').mean()
    
                  B
    Date_Time      
    2001-10-01  4.5
    2001-10-02  6.0
    

    Grouper

    As suggested by @JosephCottam

    df.set_index('Date_Time').groupby(pd.Grouper(freq='D')).mean()
    
                  B
    Date_Time      
    2001-10-01  4.5
    2001-10-02  6.0
    

    Deprecated uses of TimeGrouper

    You can set the index to be 'Date_Time' and use pd.TimeGrouper

    df.set_index('Date_Time').groupby(pd.TimeGrouper('D')).mean().dropna()
    
                  B
    Date_Time      
    2001-10-01  4.5
    2001-10-02  6.0