Sometimes, we want to GroupBy results to dictionary of lists with Python Pandas.
In this article, we’ll look at how to GroupBy results to dictionary of lists with Python Pandas.
How to GroupBy results to dictionary of lists with Python Pandas?
To GroupBy results to dictionary of lists with Python Pandas, we can use the call to_dict
after calling groupby
.
For instance, we write
d = df.groupby('Column1')['Column3'].apply(list).to_dict()
to call groupby
to group the rows by values in the Column1 column.
And then we get the grouped values in the Column3 column.
Next, we call apply
with list
to combine the grouped value into a list.
And then we call to_dict
to return a dict with the keys being the group value and the values being a list of the items in the group.
Conclusion
To GroupBy results to dictionary of lists with Python Pandas, we can use the call to_dict
after calling groupby
.