Pandas groupby(), agg(): How to return results without the multi index?

Learn, how to return the result of pandas groupby(), agg() methods without multiindex? By Pranit Sharma Last updated : October 03, 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.

Problem statement

Suppose we are given a DataFrame and we need to perform groupby and agg function on this dataframe, we get the result with a multi-index.

Getting the result of pandas groupby(), agg() methods without multiindex

We can use the reset_index() method to get rid of multiindex but it makes our program very slower and hence we need to find an alternative for this solution.

Hence, here we are going to use groupby() method first, then we will apply the agg() method on this groupby object and finally we will join the columns of groupby object with their respective values by mapping them into a list.

Let us understand with the help of an example,

Python code to get the the result of pandas groupby(), agg() methods without multiindex

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a dictionary
d = {
    'id': [9051,9051,9053,9051,9055,9055],
    'points': [100,100,200,200,178,178],
    'result':[0,1,1,0,1,1]
}

# Creating DataFrame
df = pd.DataFrame(d)

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

# Grouping columns and applying agg function
group = df.groupby(['id', 'points'], as_index=False)
res = group.agg({'result':[np.min, np.max]})

# Joining res column and values
res.columns = list(map(''.join, res.columns.values))

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

Output

The output of the above program is:

Example: Pandas groupby(), agg(): How to return results without the multi index?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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