Home > front end >  Pandas Two Columns With Text - Applying GroupBy
Pandas Two Columns With Text - Applying GroupBy

Time:04-16

I'm trying to obtain the "DESIRED OUTCOME" shown in my image below. I have a somewhat messy way to do it that i came up with but I was hoping there is a more efficient way this could be done using Pandas? Please advise and thank you in advance!

enter image description here

CodePudding user response:

The problem is pretty standard, and so is its solution: group by the first column and join the data in the second column. Note that the function join is not called but passed to apply as a parameter.

df.groupby('Name')['Food'].apply(';'.join)
#Name
#Gary    Oranges;Pizza
#John            Tacos
#Matt    Chicken;Steak

CodePudding user response:

You can group by Name column then aggregate with ';'.join function

df.groupby('Name').agg({'Food': ';'.join})
  • Related