How to Group Pandas DataFrame By Date and Time ?
In this article, we will discuss how to group by a dataframe on the basis of date and time in Pandas. We will see the way to group a timeseries dataframe by Year, Month, days, etc. Additionally, we’ll also see the way to groupby time objects like minutes.
Pandas GroupBy allows us to specify a groupby instruction for an object. This specified instruction will select a column via the key parameter of the grouper function along with the level and/or axis parameters if given, a level of the index of the target object/column.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Syntax: pandas.Grouper(key=None, level=None, freq=None, axis=0, sort=False)
Below are some examples that depict how to group by a dataframe on the basis of date and time using pandas Grouper class.
Example 1: Group by month
In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘M’ which means month, so the data is grouped month-wise till the last date of every month and provided sum of price column. We have not provided value for all months, then also groupby function displayed data for all months and assigned value 0 for other months.
Example 2: Group by days
In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘5D’ which means five days, so the data grouped by interval 5 days of every month till the last date given in the date column.
Example 3: Group by year
In the above example, the dataframe is groupby by the Date column. As we have provided freq = ‘2Y’ which means 2 years, so the data is grouped in the interval of 2 years.
Example 4: Group by minutes
In the above example, the data is grouped in intervals of every 2 minutes.