Last updated: Apr 12, 2024
Reading time·4 min
To convert the results of a groupby()
call in a Pandas DataFrame
to a
dictionary of lists:
groupby()
method on the DataFrame
, passing it the specific
column as a parameter.to_dict()
.import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = df.groupby('Animal')['Max Speed'].apply(list).to_dict() print('-' * 50) # 👇️ {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]} print(a_dict)
Running the code sample produces the following output.
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]}
We used the
DataFrame.groupby()
method to group the DataFrame
by the Animal
column.
a_dict = df.groupby('Animal')['Max Speed'].apply(list).to_dict() # 👇️ {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]} print(a_dict)
The next step is to select the column you want to have as values in the
dictionary using bracket []
notation.
The
DataFrame.apply()
method applies a function along an axis of the DataFrame
.
We used the list class to convert each row to a list.
The last step is to call the
DataFrame.to_dict()
method to convert the resulting DataFrame
to a dictionary.
You can also use a dict comprehension to convert the results of a GroupBy to a dictionary of lists.
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = { key: list(value) for key, value in df.groupby('Animal')['Max Speed'] } print('-' * 50) print(a_dict)
Running the code sample produces the following output.
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]}
Dict comprehensions are very similar to list comprehensions.
a_dict = { key: list(value) for key, value in df.groupby('Animal')['Max Speed'] }
On each iteration, we return the key and convert the value to a list to construct the dictionary.
for
loopYou can also use a simple for loop to convert
the results of a groupby()
call to a dictionary of lists.
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = {} for key, value in df.groupby('Animal')['Max Speed']: a_dict[key] = list(value) print('-' * 50) print(a_dict)
Running the code sample produces the following output.
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': [25, 35, 45], 'Dog': [55, 65, 75]}
We used a for
loop to iterate over the GroupBy
object and added the current
key and value to the new dictionary.
groupby()
result to a dictionary of DataFramesIf you want to convert the groupby()
result to a dictionary of DataFrames, use
the dict()
class.
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) print(df) a_dict = dict(tuple(df.groupby('Animal'))) print('-' * 50) print(a_dict) print('-' * 50) print(type(a_dict['Cat']))
Running the code sample produces the following output.
Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45 3 Dog 55 4 Dog 65 5 Dog 75 -------------------------------------------------- {'Cat': Animal Max Speed 0 Cat 25 1 Cat 35 2 Cat 45, 'Dog': Animal Max Speed 3 Dog 55 4 Dog 65 5 Dog 75} -------------------------------------------------- <class 'pandas.core.frame.DataFrame'>
We first used the tuple class to convert
the groupby()
result to a tuple.
import pandas as pd df = pd.DataFrame({ 'Animal': ['Cat', 'Cat', 'Cat', 'Dog', 'Dog', 'Dog'], 'Max Speed': [25, 35, 45, 55, 65, 75] }) # (('Cat', Animal Max Speed # 0 Cat 25 # 1 Cat 35 # 2 Cat 45), ('Dog', Animal Max Speed # 3 Dog 55 # 4 Dog 65 # 5 Dog 75)) print(tuple(df.groupby('Animal')))
The last step is to convert the tuple of tuples to a dictionary using the
dict()
class.
You can learn more about the related topics by checking out the following tutorials: