我有一个带有几列的 pandas 数据框(单词、开始时间、停止时间、扬声器)。我想合并“word”列中的所有值,而“speaker”列中的值不变。此外,我想保留组合中第一个单词的“开始”值和最后一个单词的“停止”值。
我目前有:
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
但是,我想把它变成:
word start start 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
我们将使用GroupBy.agg
使用 aggfuncs 字典:
(df.groupby('speaker', as_index=False, sort=False)
.agg({'word': ' '.join, 'start': 'min', 'stop': 'max',}))
speaker word start stop
0 2 but that's alright 2.72 3.47
1 1 we'll have to 8.43 9.07
要按连续出现的情况进行分组,请使用移位 cumsum 技巧,然后将其与“speaker”一起用作第二个分组:
gp1 = df['speaker'].ne(df['speaker'].shift()).cumsum()
(df.groupby(['speaker', gp1], as_index=False, sort=False)
.agg({'word': ' '.join, 'start': 'min', 'stop': 'max',}))
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)