Pandas Group by day and count for each day

Given a pandas dataframe, we have to groupby day and cunt for each day.
Submitted by Pranit Sharma, on October 19, 2022

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 a DataFrame with a column called dates, this column contains some similar and different dates. We know that each date implies someday and we need to groupby these dates or days and then we need to find the count of each date or day.

Group by day and count for each day

For grouping by day and counting for each day, we will use the following steps:

  • Create a dataframe
  • Convert the specific columns ("dates") into the datetime type using the pd.to_datetime() method by specifying the given column name.
  • Then use .dt.floor(), .value_counts(), .rename_axis(), and .reset_index() method to get the result.
  • Print the result.

Let us understand with the help of an example,

Python program to group by day and count for each day

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {'dates':['2017/06/19','2017/06/19','2017/06/19',
     '2017/06/20','2017/06/20','2017/06/23']}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original Dataframe:\n",df,"\n")

# Grouping dates and counting them
res = (pd.to_datetime(df['dates'])
       .dt.floor('d')
       .value_counts()
       .rename_axis('dates')
       .reset_index(name='count'))

# Display Result
print('Result:\n',res)

Output

The output of the above program is:

Example: Pandas Group by day and count for each day

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.