pythonpandasdatetime

How to group a datetime column by year?


I have a dataframe with a column of type datetime64[ns]. I want to group rows by year. I unsuccessfully tried

df1 = df.groupby(df.modification_datetime.year).sum()

AttributeError: 'Series' object has no attribute 'year'

Do you know how to solve that?


Solution

  • You need to use the dt accessor to extract the year from the datetime:

    df1 = df.groupby(df.modification_datetime.dt.year).sum()