Max and Min date in pandas groupby

Given a pandas dataframe, we have to find the Max and Min date in pandas groupby.
Submitted by Pranit Sharma, on September 14, 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.

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 code 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'],

# 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


Example: Max and Min date in pandas groupby

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.