GroupBy results to dictionary of lists

Given a pandas dataframe, we have groupby results to dictionary of lists.
Submitted by Pranit Sharma, on September 13, 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.

GroupBy results to dictionary of lists

Suppose, we have a DataFrame with some columns, we need to perform groupby on a column and store the result in the form of a dictionary.

Dictionaries are used to store heterogeneous data. The data is stored in key:value pair. A dictionary is a collection that is mutable and ordered in nature and does not allow duplicates which means there are unique keys in a dictionary.

A dictionary key can have any type of data as its value, for example, a list, tuple, string, or dictionary itself.

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() function split 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 code to groupby results to dictionary of lists

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[1,1,1,2,3,3,4,4],
    'B':[1020,3040,5060,7080,90100,100110,110120,120130],
    'C':[1,1,2,3,4,2,5,5]
}

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

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

# Getting group values and 
# converting to dictionary
dictionary = df.groupby('A')['C'].apply(list).to_dict()

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

Output:

Example: GroupBy results to dictionary of lists

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.