Q:

How to combine values in a row depending on value in a previous row in another column in pandas

I have a pandas dataframe with several columns (words, start time, stop time, speaker). I want to combine all values in the 'word' column while the values in the 'speaker' column do not change. In addition, I want to keep the 'start' value for the first word and the 'stop' value for the last word in the combination. Every time the speaker changes back and forth, I want to return this combination as a new row.
The first 9 rows of what I currently have are (the entire dataframe continues for a while with the speaker changing back and forth):
      word    start  stop      speaker
0      but   2.72  2.85        2
1   that's   2.85  3.09        2
2  alright   3.09  3.47        2
3    we'll   8.43  8.69        1
4     have   8.69  8.97        1
5       to   8.97  9.07        1
6     okay   9.19 10.01        2
7     sure  10.02 11.01        2
8    what?  11.02 12.00        1

However, I would like to turn this into (continuing across the entire dataframe beyond this example):
       word        start  stop speaker
0  but that's alright  2.72  3.47  2
1       we'll have to  8.43  9.07  1
2           okay sure  9.19 11.01  2
3               what? 11.02 12.00  1

A:

You need to groupby on the consecutive values of speaker.
df.groupby([(df['speaker'] != df['speaker'].shift()).cumsum(), , df['speaker']], as_index=False).agg({
    'word': ' '.join,
    'start': 'min',
    'stop': 'max'
})

Output:
   speaker                word  start   stop
0        2  but that's alright   2.72   3.47
1        1       we'll have to   8.43   9.07
2        2           okay sure   9.19  11.01
3        1               what?  11.02  12.00

