python - 根据另一列合并数据框中的行
问题描述
我已将 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 的上下文中很重要。
解决方案
您可以在创建一系列标识 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'
请注意,根据您提供的输入,输出带有引号。这些不会显示字符串是否在没有引号的情况下定义。
推荐阅读
- .net-core - Azure AD OpenIdConnect 联合使用 AddMicrosoftIdentityWebApp 和 .NET Core 3.1
- python - 如何使用前几年的 pandas.date_range 创建数据框?
- flutter - 将元素添加到列表
- javascript - NextJS:在 ExportPathMap 中设置动态路径
- c++ - 最大和最小差(贪心算法)
- android - 需要更新 firebase kotlin 中的一个字段?
- java - 在 Hibernate 中驱逐缓存时并发修改异常
- python - 如何正确计算 mp3 文件中的 ID3v2 标签大小?
- python - Python:使用坐标从 Excel 中读取单元格
- python - 如何从 subproces.run() 运行 pip install 命令