How to get first and last values in a groupby?

Learn, how to get the first and last values in a group by object?
Submitted by Pranit Sharma, on November 05, 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.

Suppose we are given a DataFrame with two columns and some values, we need to perform groupby operation on this DataFrame and then we will apply aggregate function on this object and pass the aggregate first and last parameters in a list.

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

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

To present our output in a tabular fashion or a more readable format, we will apply the stack() method to our result so that all the first and last rows will be represented one below another.

Let us understand with the help of an example,

Python code to get first and last values in a groupby

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame(np.arange(20).reshape(10, -1),
    [['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
    ['X', 'Y'])

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Performing groupby on df
gp = df.groupby(level=0)

# Applying aggregate function
res = gp.agg(['first', 'last'])

# Using stack method
res = res.stack()

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

Output:

Example: Get first and last values in a groupby?

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




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

© https://www.includehelp.com some rights reserved.