Categories
Python Answers

How to get a union of strings with Python Pandas groupby?

Spread the love

Sometimes, we want to get a union of strings with Python Pandas groupby.

In this article, we’ll look at how to get a union of strings with Python Pandas groupby.

How to get a union of strings with Python Pandas groupby?

To get a union of strings with Python Pandas groupby, we can use the groupby method with the apply method.

For instance, we write

l = d.groupby('A')['B'].apply(list)

to call groupby with 'A' to group the rows in the d data frame by the values of column A.

Then we get the values of column B from the grouped items.

Next, we call apply with list to put the grouped items into their own list separated by group and return a new data frame with the values.

Conclusion

To get a union of strings with Python Pandas groupby, we can use the groupby method with the apply method.

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 *