I have an Input Dataframe that the following :
NAME TEXT
Tim Tim Wagner is a teacher.
Tim He is from Cleveland, Ohio.
Frank Frank is a musician.
Tim He like to travel with his family
Frank He is a performing artist who plays the cello.
Frank He performed at the Carnegie Hall last year.
Frank It was fantastic listening to him.
I want to concatenate TEXT column if the consecutive rows of NAME column have the same value.
Output Dataframe:
NAME TEXT
Tim Tim Wagner is a teacher. He is from Cleveland, Ohio.
Frank Frank is a musician
Tim He like to travel with his family
Frank He is a performing artist who plays the cello. He performed at the Carnegie Hall last year. It was fantastic listening to him.
Is using pandas shift, the best way to do this? Appreciate any help
thanks
Try:
grp = (df['Name'] != df['NAME'].shift()).cumsum().rename('group')
df.groupby(['NAME', grp], sort=False)['TEXT']\
.agg(' '.join).reset_index().drop('group', axis=1)
Output:
NAME TEXT
0 Tim Tim Wagner is a teacher. He is from Cleveland,...
1 Frank Frank is a musician
2 Tim He likes to travel with his family
3 Frank He is a performing artist who plays the cello....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With