Max and Min date in pandas groupby

Given a pandas dataframe, we have to find the Max and Min date in pandas groupby. By Pranit Sharma Last updated : September 30, 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.

Finding the Max and Min date in pandas groupby

To find max and min date in pandas groupby, we will first create a DataFrame with some dates in a column and then we will use groupby() method.

The groupby() is a simple but very useful concept in pandas. By using it, we can create grouping of certain values and perform some operations on those values.

The groupby() method splits the object, applies some operations, and then combines them to create a group hence large amount of data and computations can be performed on these groups.

The groupby() operation packs the data into an object and if we want to check out that data, we need to access that object.
We will then use the max and min method of NumPy so that we can find the max and min values from groupby.

Let us understand with the help of an example,

Python program to find the max and min date in pandas groupby

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'date':['2018-06-22 10:46:00', '2019-07-14 19:52:00', '2020-08-01 17:02:00', '2021-09-25 13:35:20'],
    'code':['A','A','B','B'],
    'sum':[21,21,13,13]
}

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

# Display DataFrame
print("Created DataFrame:\n",df)

# grouping the items
group = df.groupby(['code', 'sum'])

# finding max and min date
result = group.agg({ 'date' : [np.min, np.max]})

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Max and Min date in pandas groupby

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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