python - pandas:连接字符串行直到特定字符
问题描述
我有一个单列数据框。该列的行包含通常跨越多行的对话。每个人对话行的末尾都是相同的字符“&,”组合,如下所示:
Words
1 hello world! &,,
2 I woke up this morning and made some eggs.
3 They tasted good. &,,
我想将不以“&,”结尾的每一行与下一行合并,这样每一行都是一个不同的人在说话,而不是同一段落的多行。它看起来像这样:
Words
1 hello world! &,,
2 I woke up this morning and made some eggs. They tasted good. &,,
我看到的每个与此类似的问题都涉及另一列,该列将指定一些额外的信息,例如,它可能会说谁在说话,但是对于这个数据集,我没有那个,我也没有另一个包含更多信息的数据集,所有我有的是分隔符。
解决方案
您可以使用df['Words'].str.endswith('&,,')
来查找以 结尾的行&,,
,然后用于cumsum
生成所需的组号(存储在下面的row
列中)。获得这些组编号后,您可以使用pd.pivot_table
将 DataFrame 重塑为所需的形式:
import sys
import pandas as pd
pd.options.display.max_colwidth = sys.maxsize
df = pd.DataFrame({
'Words': ['hello world! &,,',
'I woke up this morning and made some eggs.',
'They tasted good. &,,']}, index=[1, 2, 3])
df['row'] = df['Words'].str.endswith('&,,').shift().fillna(0).cumsum() + 1
result = pd.pivot_table(df, index='row', values='Words', aggfunc=' '.join)
print(result)
产量
Words
row
1 hello world! &,,
2 I woke up this morning and made some eggs. They tasted good. &,,
推荐阅读
- c# - 获取 textBlock 的高度时,无论实际高度如何,它都会显示相同的数字
- arrays - 我如何找到两张牌的总和?
- node.js - 监控和刷新 PubSub 批处理发布者队列
- go - Is it safe to write files in mode os.O_APPEND|os.O_WRONLY?
- file - 如何将不同类型的数据存储在一个文件中
- tree - 使 C 不平衡的两个子树是什么?
- html - 链接内的 HTML
- django - “profile_picture”属性没有与之关联的文件
- python - 球拍:双冒号 (::) 是什么意思?
- ios - iPhoneX:将tableview一直延伸到显示器底部(非安全区域)