Home »
Python »
Python Programs
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
Prerequisite
- Pandas: 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.
- Dictionaries: 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.
- groupby() Method: 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.
Problem statement
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.
GroupBy results to dictionary of lists
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 program 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
The output of the above program will be:
Python Pandas Programs »