Get all keys from GroupBy object in Pandas

Given a pandas dataframe, we have to get all keys from GroupBy object in Pandas.
Submitted by Pranit Sharma, on September 15, 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.

Problem statement

Given a pandas dataframe, we have to get all keys from GroupBy object in Pandas.

Getting all keys from GroupBy object

For this purpose, we will use df.groupby() method, it 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.

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

Basically, the groupby operation packs the data into an object and if we want to check out that data, we need to access that object and we are going to get all the keys to this object.

Let us understand with the help of an example,

Python program to get all keys from GroupBy object in pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'sports':['Football','cricket',
               'basketball','volleyball',
               'rugby','baseball',
               'badminton','hockey'],
    'no_of_people_like':[33,33,29,12,28,28,28,12]
}

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

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

# using groupby
group = df.groupby('no_of_people_like')

# Getting keys of groupby object
res = group.groups.keys()

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

Output

The output of the above program is:

Get all keys from GroupBy object in Pandas

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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