Home »
Python »
Python Programs
How can I group by month from a date field using Python and Pandas?
Learn, how to group by month from a date field using Python and Pandas?
By Pranit Sharma Last updated : October 06, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose we are given the data frame with a column containing date type values and another column containing some numerical values we need to group the data of this data frame in such a way that the data is grouped by month which depends on the date of the date column and we need to add all the values corresponding to the grouped month.
Group by month from a date field using Python and Pandas
For this purpose, we will first convert the date column into DateTime type and then we will group by this column and use the sum method on the grouped object.
Let us understand with the help of an example,
Python program to group by month from a date field using Python and Pandas
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating DataFrame
df = pd.DataFrame({
'date':[ '07/12/2001','07/12/2000','05/10/1999','05/10/1998','03/08/1997'],
'Values':[21,22,23,24,25]
})
# Display Original dataframe
print("Original DataFrame:\n",df,"\n")
# Converting date to datetime column
df['date'] = pd.to_datetime(df['date'])
# Grouping values and applying sum
res = df.groupby(df['date'].dt.strftime('%B'))['Values'].sum().sort_values()
# Print result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »