Menu Close

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

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.

Posted in Python, Python Answers