Categories
Python Answers

How to GroupBy results to dictionary of lists with Python Pandas?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *