Skip to content
Advertisement

Pandas – Merge rows of dataframe that have a shared value

I have a dataframe with a list of items in the first row and then all the items that were bought with that item in subsequent columns:

JavaScript

I want to merge all the items bought with each item into a single row as below:

JavaScript

So, all the items bought with Item 1 form the columns next to it. As you can see in my example I want to keep all items that were bought with each item, even if they are duplicated.

I have been trying to get it to work with a pandas dataframe, however if there was a list generated for each item that would also be fine. I have been trying some kind of groupby and lambda function but I can’t get them to work.

EDIT: Changed numbers to make it more clear how the final df should be organized.

Thanks!

Advertisement

Answer

TRY:

JavaScript

OUTPUT:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement