首页 > 解决方案 > 根据另一列合并数据框中的行

问题描述

我已将 pdf 提取到数据框中,如果 B 列是同一扬声器,我想合并行:

从 :

  Index     Column B     Column C 
   1       'I am going'    Speaker A 
   2       'to the zoo'    Speaker A
   3       'I am going'    Speaker B 
   4       'home      '    Speaker B
   5       'I am going'    Speaker A 
   6       'to the park'   Speaker A

至 :

  Index     Column B                    Column C 
   1       'I am going to the zoo '    Speaker A 
   2       'I am going home'           Speaker B
   3       'I am going to the park'    Speaker A 

我尝试使用 groupby 但顺序在作为演讲的 pdf 的上下文中很重要。

标签: pythonstringdataframejoinpandas-groupby

解决方案


您可以在创建一系列标识 C 列何时更改后使用GroupBy+ :agg

res = df.assign(key=df['Column C'].ne(df['Column C'].shift()).cumsum())\
        .groupby('key').agg({'Column C': 'first', 'Column B': ' '.join})\
        .reset_index()

print(res)

   key   Column C                    Column B
0    1  Speaker A   'I am going' 'to the zoo'
1    2  Speaker B   'I am going' 'home      '
2    3  Speaker A  'I am going' 'to the park'

请注意,根据您提供的输入,输出带有引号。这些不会显示字符串是否在没有引号的情况下定义。


推荐阅读