Categories
Python Answers

How to use groupby results to dictionary of lists with Python Pandas?

Spread the love

Sometimes, we want to use groupby results to dictionary of lists with Python Pandas.

In this article, we’ll look at how to use groupby results to dictionary of lists with Python Pandas.

How to use groupby results to dictionary of lists with Python Pandas?

To use groupby results to dictionary of lists with Python Pandas, we can us the apply and to_dict methods.

For instance, we write

df.groupby('Column1')['Column3'].apply(list).to_dict()

to call groupby with 'Column1 to group the df data frame values by Column1.

And then we get the values from Column3 from the grouped results.

And then we call apply with list to convert the result to a list.

Finally, we call to_dict to convert the dict to a dictionary.

Conclusion

To use groupby results to dictionary of lists with Python Pandas, we can us the apply and to_dict methods.

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 *