×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Pandas GroupBy get list of groups

Learn, how can we get groupby list of groups in pandas DataFrame? 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.

Problem statement

Suppose, we have a DataFrame with multiple columns along with a specific column called fruits. Fruits contain multiple values. Now after grouping the values of fruits, we need to get the list of all the group values.

GroupBy get list of groups

For this purpose, we will use the DataFrame.groupby() method by passing the specified column and then use the .groups.keys() method on the result. Consider the below-given code snippet to achieve this task,

group = df.groupby('fruits')
group = group.groups.keys()

The groupby() method

The groupby() is a simple but very useful concept in pandas. By using groupby(), we can create grouping of certain values and perform some operations on those values. This method splits the object, apply some operations, and then combines them to create a group hence a large amount of data and computations can be performed on these groups.

Let us understand with the help of an example,

Python program for Pandas GroupBy get list of groups

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[1,2,3,4,5,6],
    'B':[1,2,3,4,5,6],
    'fruits':['mango','apple','grape','mango','apple','guava']
}

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

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

# Getting group values of fruits
group = df.groupby('fruits')
group = group.groups.keys()

# Display group values
print("Result:\n",group)

Output

The output of the above program is:

Example: Pandas GroupBy get list of groups

Python Pandas Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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